简体   繁体   中英

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? I wish to add all of the values of 'test' found in the array, so it'd come up with '214' for example. 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:

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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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