supposing I have a multidimensional associative array:
$haystack =
[
"httpMethod" => "GET",
"responseFormat" => "",
"query" => [
"uname" => "username",
"pass" => "password"
]
];
And I have another simple array:
$needle = [
"username" => "123",
"password" => "456"
];
My goal is to search the first one recursively where the value say "username", and replace it with the value from the second array.
So the Array returned of this would be:
$result = [
"httpMethod" => "GET",
"responseFormat" => "",
"query" => [
"uname" => "123",
"pass" => "456"
]
];
What is the most effective most readable way to do that? knowing the haystack-array can be differently structured.
Try array_walk_recursive(), any key that holds an array will not be passed to the function.
array_walk_recursive( $haystack, function( &$item, $key ) use ( $needle ) {
if ( array_key_exists( $item, $needle ) )
$item = $needle[ $item ];
});
0 comments:
Post a Comment