user818991
user818991

Reputation:

PHP multidimensional array get value by key

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

Upvotes: 2

Views: 2249

Answers (2)

Robert
Robert

Reputation: 20286

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"

Upvotes: 0

hsz
hsz

Reputation: 152216

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)

Upvotes: 4

Related Questions