Count total of subarrays with certain values in PHP

前端 未结 2 1203
夕颜
夕颜 2021-01-23 16:28
$example = 
  array
    \'test\' =>
      array(
        \'something\' => \'value\'
      ),
    \'whatever\' =>
      array(
        \'something\' => \'othe         


        
相关标签:
2条回答
  • 2021-01-23 16:38

    array_filter() is what you need:

    count(array_filter($example, function($element){
    
        return $element['something'] == 'other';
    
    }));
    

    In case you want to be more flexible:

    $key = 'something';
    $value = 'other';
    
    $c = count(array_filter($example, function($element) use($key, $value){
    
        return $element[$key] == $value;
    
    }));
    
    0 讨论(0)
  • 2021-01-23 16:53

    You can try the following:

    $count = 0;
    foreach( $example as $value ) {
        if( in_array("other", $value ) )
            $count++;
    }
    
    0 讨论(0)
提交回复
热议问题