Counting Values in Multidimensional Array

前端 未结 5 2056
慢半拍i
慢半拍i 2020-12-03 18:22

I currently have the following array:

Array(
        [0] => Array
            (
                [user] => Name 1
                [group] => 1
               


        
相关标签:
5条回答
  • 2020-12-03 18:29

    This can be done with a simple iteration:

    $counts = array();
    foreach ($array as $key=>$subarr) {
      // Add to the current group count if it exists
      if (isset($counts[$subarr['group']]) {
        $counts[$subarr['group']]++;
      }
      // or initialize to 1 if it doesn't exist
      else $counts[$subarr['group']] = 1;
    
      // Or the ternary one-liner version 
      // instead of the preceding if/else block
      $counts[$subarr['group']] = isset($counts[$subarr['group']]) ? $counts[$subarr['group']]++ : 1;
    }
    

    Update for PHP 5.5

    In PHP 5.5, which has added the array_column() function to aggregate an inner key from a 2D array, this can be simplified to:

    $counts = array_count_values(array_flip(array_column($array, 'group')));
    
    0 讨论(0)
  • 2020-12-03 18:29
    $output = array();
      foreach($data as $key => $value){
        $output[$value['group']]['count']++;
    }
    
    $final = array();
    foreach($output as $key => $value){
        $final[$key] = $value['count'];    
    }
    
    print_r($final);
    
    //out put result:=========
    Array(
        [1] => 2
        [2] => 2
        [3] => 1
    )
    
    0 讨论(0)
  • 2020-12-03 18:33

    Try this simple but effective way

    $count = call_user_func_array('array_merge_recursive', $Array);
    echo count($count['user']).'<br>';
    echo count($count['group']).'<br>';
    
    0 讨论(0)
  • 2020-12-03 18:44

    Your initial attempt was close. You were simply using the wrong key inside the loop:

    $newArr = array();
    foreach ($details['user_groups'] as $key => $value) {
            // What you were using:
            // $newArr[$value['user_groups']]++;
    
            // What you should be using:
            $newArr[$value['group']]++;
    }
    
    0 讨论(0)
  • 2020-12-03 18:45

    This can be done with a simple array_map function

    $array = array_map(function($element){
        return $element['group'];
    }, $array1);
    
    $array2 = (array_count_values($array));
    
    print_r($array2);
    
    0 讨论(0)
提交回复
热议问题