Grouping arrays in PHP

后端 未结 5 982
广开言路
广开言路 2020-12-01 08:22

I have an array of 200 items. I would like to output the array but group the items with a common value. Similar to SQL\'s GROUP BY method. This should be relatively easy to

相关标签:
5条回答
  • 2020-12-01 08:58

    Just iterate over the array and use another array for the groups. It should be fast enough and is probably faster than the overhead involved when using sqlite or similar.

    $groups = array();
    foreach ($data as $item) {
        $key = $item['key_to_group'];
        if (!isset($groups[$key])) {
            $groups[$key] = array(
                'items' => array($item),
                'count' => 1,
            );
        } else {
            $groups[$key]['items'][] = $item;
            $groups[$key]['count'] += 1;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 08:58
    $groups = array();
    foreach($items as $item)
        $groups[$item['value']][] = $item;
    foreach($groups as $value => $items)
        echo 'Group ' . $value . ' has ' . count($items) . ' ' . (count($items) == 1 ? 'item' : 'items') . "\n";
    
    0 讨论(0)
  • 2020-12-01 09:13
    $aA = array_count_values(array(1,2,3,4,5,1,2,3,4,5,6,1,1,1,2,2));
    $aB = array();
    foreach($aA as $index=>$aux){
         array_push($aB,$index);
    }
    print_r($aB);
    

    Result:

    Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) 
    
    0 讨论(0)
  • "$Switches" Array with [3] elements
    0       
        SwitchID    1   
        name    k�  
        type    output  
        displayAs   button  
        value   on  
        groupname   group1  
    1   Array [6]   
    2   Array [6]   
    
    
    // this will sort after groupname
    
    $result = array();
    $target = count($Switches);
    for($i=0;$i<$target;$i++)
    {
        $groupname = $Switches[$i]["groupname"];
    
        $result[$groupname][] = $Switches[$i];
    }
    
    // count amount of groups
    $groupCount = count($result);
    

    ... or did i miss something?

    0 讨论(0)
  • 2020-12-01 09:18

    Here's a quick example:

    $a = array(1, 2, 3, 1, 2, 3, 3, 2, 3, 2, 3, 4, 4, 1);
    $n = array_count_values($a);
    arsort($n);
    

    print_r($n);

    Array ( [3] => 5 [2] => 4 [1] => 3 [4] => 2 )

    0 讨论(0)
提交回复
热议问题