How to group the array by the same key and value

后端 未结 2 1659
粉色の甜心
粉色の甜心 2020-12-24 08:56

I have an array like this:D

Array
(
[0] => Array
    (
        [type] => AAA
        [label_id] => A1,35
    )

[1] => Array
    (
        [type]         


        
相关标签:
2条回答
  • 2020-12-24 09:31

    This should do the trick

    $args = array
    (
        array( 'type' => 'AAA', 'label_id' => 'A1,35' ),
        array( 'type' => 'AAA', 'label_id' => 'A2,34' ),
        array( 'type' => 'BBB', 'label_id' => 'B1,29' ),
        array( 'type' => 'CCC', 'label_id' => 'C1,20' ),
        array( 'type' => 'CCC', 'label_id' => 'C2,19' ),
        array( 'type' => 'CCC', 'label_id' => 'C3,18' )  
    );
    
    $tmp = array();
    
    foreach($args as $arg)
    {
        $tmp[$arg['type']][] = $arg['label_id'];
    }
    
    $output = array();
    
    foreach($tmp as $type => $labels)
    {
        $output[] = array(
            'type' => $type,
            'label_id' => $labels
        );
    }
    
    var_dump($output);
    

    The output is :

    array
      0 => 
        array
          'type' => string 'AAA' (length=3)
          'label_id' => 
            array
              0 => string 'A1,35' (length=5)
              1 => string 'A2,34' (length=5)
      1 => 
        array
          'type' => string 'BBB' (length=3)
          'label_id' => 
            array
              0 => string 'B1,29' (length=5)
      2 => 
        array
          'type' => string 'CCC' (length=3)
          'label_id' => 
            array
              0 => string 'C1,20' (length=5)
              1 => string 'C2,19' (length=5)
              2 => string 'C3,18' (length=5)
    
    0 讨论(0)
  • 2020-12-24 09:34
    <?php
    
    $grouped_types = array();
    
    foreach($types as $type){
            $grouped_types[$type['type']][] = $type;
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题