简体   繁体   English

PHP多维数组通过键获取价值

[英]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'. 我已经开始写一堆嵌套的foreach和if / isset了,但是它不是很有效,感觉有点“错”。 I'm fairly familiar with PHP but a bit stuck with this one. 我对PHP相当熟悉,但对此却有些犹豫。

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. 例如,无论数组中的位置如何,都从“ sub_key”获取所有值。

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 编辑 :我现在看到的问题是我的“ sub_key”是一个数组,因此不包含在结果中,按照这里的第一个评论http://php.net/manual/en/function.array-walk-recursive.php

Just try with array_walk_recursive : 只需尝试使用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. array_walk_recursive()遍历数组的每个元素,您可以应用用户定义的函数。 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" 在将函数应用于每个元素之后,每个键的值将等于“ sub_key”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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