在PHP中合并具有相同id值的数组元素

时间:2015-11-03 23:53:17

标签: php arrays

我在PHP中使用了follow数组。 对于相同的Id值,Id和Total键是相同的。

Array
(
    [0] => Array
        (
            [id]    => 1
            [total] => 100
            [line]  => books
            [value] => 10
        )
    [1] => Array
        (
            [id]    => 1
            [total] => 100
            [line]  => cars
            [value] => 50
        )
    [2] => Array
        (
            [id]    => 1
            [total] => 100
            [line]  => cover
            [value] => 30
        )
    [3] => Array
        (
            [id]    => 2
            [total] => 80
            [line]  => books
            [value] => 5
        )
    [4] => Array
        (
            [id]    => 2
            [total] => 80
            [line]  => cover
            [value] => 35
        )
    [5] => Array
        (
            [id]    => 2
            [total] => 80
            [line]  => cars
            [value] => 40
        )

我想在一个数组中合并Line和Value元素。 为了说明我正在寻找的结果是以下数组。

Array
(
    [0] => Array
        (
            [id]      => 1
            [total]   => 100
            [details] => Array
               (
                   [0] => Array
                      (
                         [line]  => books
                         [value] => 10
                      )
                   [1] => Array
                      (
                         [line]  => cars
                         [value] => 50
                      )
                   [2] => Array
                      (
                         [line]  => cover
                         [value] => 30
                      )
               ) 
        )                      

    )
    [1] => Array
        (
            [id]      => 2
            [total]   => 80
            [details] => Array
               (
                   [0] => Array
                      (
                         [line]  => books
                         [value] => 5
                      )
                   [1] => Array
                      (
                         [line]  => cars
                         [value] => 35
                      )
                   [2] => Array
                      (
                         [line]  => cover
                         [value] => 40
                      )
               ) 
        )                      
    )

我正在使用PHP。谢谢你的帮助。

1 个答案:

答案 0 :(得分:6)

非常无聊,无法为你完成工作\功课:

$out=array();
foreach($array as $x){
  $out[$x['id']]['id']=$x['id'];
  $out[$x['id']]['total']=$x['total'];
  $out[$x['id']]['details'][]=array('line'=>$x['line'],'value'=>$x['value']);
}

注意:

  • 使用id作为out键,可以添加我们自己的,但这将有效 精细。
  • id和total将在每个循环(每个键)上被覆盖,但这没什么大不了的。
  • line \ value递增到自己的详细信息数组