【问题标题】:PHP: How do I search an array for all entries of a specific key and return value?PHP:如何在数组中搜索特定键和返回值的所有条目?
【发布时间】:2011-01-04 11:44:25
【问题描述】:

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

$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”。数组的深度应该是任意的,但是无论如何key都是一样的。

【问题讨论】:

    标签: php search arrays recursion


    【解决方案1】:

    处理递归数组。

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

    【讨论】:

    • +1。我认为您的意思是 $total += recursiveSum(...),而不是 $total += sumOfKeys(...)
    • 当我们不使用工具重构时会发生这种情况:)
    【解决方案2】:

    为此使用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 对象?因为否则你必须用一个全局变量来计算总数,这没问题,但可能会很乱。对象通过引用传递。您可以使用该对象来控制诸如搜索什么键之类的事情。

    【讨论】:

      【解决方案3】:
      $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;  
      }
      

      任何深度。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多