views:

108

answers:

2

Hi all,

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!

+5  A: 

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.

Kitson
Apologies, I forgot to mention, what if I want to check if the keys are the same in a multidimensional way: `$item['wantedkey1']['wantedkey2']`How do I make sure both keys are present?
Jasie
A: 

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?

Splash
The only disadvantage to this is that you would throw exceptions if the `$subarray` didn't contain an `'wantedkey'`.
Kitson