繁体   English   中英

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

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

我有一个多维数组,例如:

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

如何在数组中搜索所有键'test'并获取值? 我希望在数组中添加'test'的所有值,所以它会以'214'为例。 阵列应该是任何深度,但无论如何关键都是相同的。

处理递归数组。

$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");

使用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;

为什么有Sum对象? 因为否则你必须使用全局变量计算总数,这可以,但可能是凌乱的。 对象通过引用传递。 您可以使用该对象来控制搜索键或其他任何键。

$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;  
}

任何深度。

暂无
暂无

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

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