php – 如何使用相同的键和值对数组进行分组

前端之家收集整理的这篇文章主要介绍了php – 如何使用相同的键和值对数组进行分组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个这样的数组:D
Array
(
[0] => Array
    (
        [type] => AAA
        [label_id] => A1,35
    )

[1] => Array
    (
        [type] => AAA
        [label_id] => A2,34
    )

[2] => Array
    (
        [type] => BBB
        [label_id] => B1,29
    )

[3] => Array
    (
        [type] => CCC
        [label_id] => C1,20
    )

[4] => Array
    (
        [type] => CCC
        [label_id] => C2,19
    )

[5] => Array
    (
        [type] => CCC
        [label_id] => C3,18
    )
)

现在我想用同样的关键和价值使它成为一个这样的组合.

Array
(
[0] => Array
    (
        [type] => AAA
        [label_id] => Array
            (
                [0] => A1,35
                [1] => A2,34
            )
    )
[1] => Array
    (
        [type] => BBB
        [label_id] => Array
            (
                [0] => B1,29
            )
    )
[2] => Array
    (
        [type] => CCC
        [label_id] => Array
            (
                [0] => C1,20
                [1] => C2,19
                [2] => C3,18
            )
   )
   )

有谁知道该怎么做?

这应该是诀窍
$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' ),'label_id' => 'C2,19' ),'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);

输出为:

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)
原文链接:https://www.f2er.com/php/131995.html

猜你在找的PHP相关文章