简体   繁体   中英

PHP multidimensional array get value by key

I have a multi array eg

$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.

Eg 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

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)

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"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM