2

I have a multi array e.g

$a = array(
  'key' => array(
    'sub_key' => 'val'
 ),
 'dif_key' => array(
   'key' => array(
     'sub_key' => 'val'
   )
 )
);

The real array I have is quite large and the keys are all at different positions.

I've started to write a bunch of nested foreach and if/isset but it's not quite working and feels a bit 'wrong'. I'm fairly familiar with PHP but a bit stuck with this one.

Is there a built in function or a best practise way that I can access all values based on the key name regardless of where it is.

E.g get all values from 'sub_key' regardless of position in array.

EDIT: I see now the problem is that my "sub_key" is an array and therefore not included in the results as per the first comment here http://php.net/manual/en/function.array-walk-recursive.php

3
  • 1
    please add the code which you have tried. it ll he helpful to orrect you. Commented Nov 9, 2015 at 7:45
  • Duplicate? stackoverflow.com/questions/7994497/… Commented Nov 9, 2015 at 7:48
  • you can use array_column function Commented Nov 9, 2015 at 8:10

2 Answers 2

4

Just try with array_walk_recursive:

$output = [];
array_walk_recursive($input, function ($value, $key) use (&$output) {
    if ($key === 'sub_key') {
        $output[] = $value;
    }
});

Output:

array (size=2)
  0 => string 'val' (length=3)
  1 => string 'val' (length=3)
Sign up to request clarification or add additional context in comments.

1 Comment

I see now the problem is that my "sub_key" is an array and therefore not included in the results as per the first comment here php.net/manual/en/function.array-walk-recursive.php
0

You can do something like

$a = [
  'key' => [
    'sub_key' => 'val'
  ],
 'dif_key' => [
   'key' => [
     'sub_key' => 'val'
   ]
 ]
];

$values = [];

array_walk_recursive($a, function($v, $k, $u) use (&$values){
    if($k == "sub_key") {
       $values[] = $v;
    }
},  $values );

print_r($values);

How does it work?

array_walk_recursive() walks by every element of an array resursivly and you can apply user defined function. I created an anonymous function and pass an empty array via reference. In this anonymous function I check if element key is correct and if so it adds element to array. After function is applied to every element you will have values of each key that is equal to "sub_key"

1 Comment

I see now the problem is that my "sub_key" is an array and therefore not included in the results as per the first comment here php.net/manual/en/function.array-walk-recursive.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.