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

在PHP中有以下数组.Id和Total键对于相同的Id值是相同的.数组如下: 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] = Arr

在PHP中有以下数组.Id和Total键对于相同的Id值是相同的.数组如下:
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
                      )
               ) 
        )                      
    )
实现代码如下:
$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递增到自己的details数组

本文标题为:PHP中合并具有相同id值的数组元素

基础教程推荐