I have a PHP array like this (sans syntax):
array
(
['one'] => array (
['wantedkey'] => 5
['otherkey1'] => 6
['otherkey2'] => 7
)
['two'] => => array (
['otherkey1'] => 5
['otherkey2'] => 6
['wantedkey'] => 7
)
['three'] => => array (
['otherkey1'] => 5
['wantedkey'] => 6
['otherkey2'] => 7
)
)
What's the best way to print the values for only the elements with a key of 'wantedkey'
, if I'm using array_walk_recursive
for example?
Thanks!
Wouldn't something like this work?
function test_print($item, $key) {
if ($key === 'wantedkey') {
print $item;
}
}
array_walk_recursive($myarray, 'test_print');
Or am I missing something in your requirements? [I guess I was]
So the best way I can thing of handling what you are looking for would be something like:
function inner_walk ($item, $key) {
if ($key === 'wantedkey2') {
print $item;
}
}
function outer_walk ($item, $key) {
if (($key === 'wantedkey1') && (is_array($item)) {
array_walk($item,'inner_walk');
}
}
array_walk($myarray,'outer_walk');
The problem with array_walk_recursive
is that it doesn't actually tell you where you are in the array. You could in theory apply something similiar with array_walk_recursive
to the above, but since you only presented a two dimensional array, using array_walk
should work just fine.
I may be mising something here too, but why not just foreach over them?
foreach($myarray as $subarray) {
echo $subarray['wantedkey'];
}
Doesn't directly answer your original question since its not using array_walk_recursive
, but it would seem to do what you ask with less complexity. Have I misunderstood?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.