1

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?

New requirement from comment under answer:

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?

mickmackusa
  • 37,596
  • 11
  • 75
  • 105
atp
  • 28,762
  • 44
  • 122
  • 183
  • This question is missing its desired result. I don't see why `array_column()` is not being used. Do you want to return the whole subarray? – mickmackusa Feb 19 '22 at 11:50

2 Answers2

5

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
  • 1,640
  • 1
  • 18
  • 35
  • 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? – atp Dec 23 '09 at 18:52
0

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?

Mark Embling
  • 12,379
  • 6
  • 38
  • 53
  • The only disadvantage to this is that you would throw exceptions if the `$subarray` didn't contain an `'wantedkey'`. – Kitson Dec 23 '09 at 13:52