简体   繁体   English

PHP:如何在数组中搜索特定键的所有条目并返回值?

[英]PHP: How do I search an array for all entries of a specific key and return value?

I've got a multidimentional array such as: 我有一个多维数组,例如:

$array = array(
  array('test'=>23, 'one'=>'etc' , 'blah'=>'blah'),
  array('test'=>123, 'one'=>'etc' , 'blah'=>'blah'),
  array('test'=>33, 'one'=>'etc' , 'blah'=>'blah'),
);

How to I search the array for all the keys 'test' and get the value? 如何在数组中搜索所有键'test'并获取值? I wish to add all of the values of 'test' found in the array, so it'd come up with '214' for example. 我希望在数组中添加'test'的所有值,所以它会以'214'为例。 The array should be any depth but the key will be the same no matter what. 阵列应该是任何深度,但无论如何关键都是相同的。

To handle recursive arrays. 处理递归数组。

$array = array(
  array('test' => 23, 'one' => array("a" => "something", "test" => 28), 'blah' => array("test" => 21)),
  array('test' => 123, 'one' => 'etc' , 'blah' => 'blah'),
  array('test' => 33, 'one' => 'etc' , 'blah' => 'blah'),
);

function recursiveSum($array, $keyToSearch) {
    $total = 0;
    foreach($array as $key => $value) {
        if(is_array($value)) {
            $total += recursiveSum($value, $keyToSearch);
        }
        else if($key == $keyToSearch) {
            $total += $value;
        }
    }
    return $total;
}

$total = recursiveSum($array, "test");

Use array_walk_recursive() for this: 使用array_walk_recursive()

class Sum { public $total = 0; }
$sum = new Sum;
array_walk_recursive($array, 'add_test', $sum);

function add_test($item, $key, $sum) {
  if ($key == 'test') {
    $sum->total += $item;
  }
}

print $sum->total;

Why have the Sum object? 为什么有Sum对象? Because otherwise you have to work out the total with a global variable, which is OK but possibly messy. 因为否则你必须使用全局变量计算总数,这可以,但可能是凌乱的。 Objects are passed by reference. 对象通过引用传递。 You could use the object to control things like what key to search for or whatever too. 您可以使用该对象来控制搜索键或其他任何键。

$total = 0;
function crawl( $array ) {
    global $total;

    if( is_array( $array ) ) {
        foreach( $array as $key=>$val ) {

            if( $key === "test" ) {             
                $total = $total + $val;             
            }

            crawl( $val );          
        }
    }

    return $total;  
}

Any depth. 任何深度。

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

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