[英]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");
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.