将二维数组的行数据按一列分组,并将其他列推送到每组内的子数组中

问题描述 投票:0回答:4

我有一个像这样的数组:

Array(
[0] => Array
    (
        [id] => 1
        [order_sn] => EU/2011/04/PO/5
        [total] => 65
    )

[1] => Array
    (
        [id] => 1
        [order_sn] => EU/2011/04/RS/4
        [total] => 230
    )

[2] => Array
    (
        [id] => 1
        [order_sn] => EU/2011/04/RS/3
        [total] => 130
    )

[3] => Array
    (
        [id] => 2
        [order_sn] => EU/2011/04/RS/2
        [total] => 100
    )
[4] => Array
    (
        [id] => 2
        [order_sn] => EU/2011/04/RS/1
        [total] => 60
    )
)

如果数组具有相同的键值,如何合并它们...?

我需要得到的结果是这样的...

Array(
    [0] => Array
        (
            [id] => 1
            [detail] => Array 
            (
                [0] => Array 
                (
                    [order_sn] => EU/2011/04/PO/5
                    [total] => 65
                )
                [1] => Array
                (
                    [order_sn] => EU/2011/04/RS/4
                    [total] => 230
                )
                [2] => Array
                (
                    [order_sn] => EU/2011/04/RS/3
                    [total] => 130
                )
            )
        )

    [1] => Array
        (
            [id] => 2
            [detail] => Array 
            (
                [0] => Array 
                (
                    [order_sn] => EU/2011/04/RS/2
                    [total] => 100
                )
                [1] => Array
                (
                    [order_sn] => EU/2011/04/RS/1
                    [total] => 60
                )
            )
        )
)

对于这种情况我应该使用什么方法?

php arrays multidimensional-array grouping sub-array
4个回答
3
投票

尝试这样:

<?php
$result = array();
foreach ($my_array as $v) {
  $id = $v['id'];
  $result[$id]['id'] = $id;
  $result[$id]['detail'][] = array(
    'order_sn' => $v['order_sn'],
    'total'    => $v['total'],
  );
}

0
投票

您可以循环遍历数组并构建一个结果数组:

// $a is your array
$r=array();
foreach($a as $v)
    $r[$v['id']][]=array('order_sn'=>$v['order_sn'], 'total'=>$v['total']);
echo'<pre>';
var_dump($r);

由于您通过 ID 进行配对,因此明智的做法是将其作为键,并将与其关联的所有数据作为值。没必要同时拥有

id
detail


0
投票
foreach($origianlArray as $key => $value){

 $newArray[$value['id']]['id'] = $value['id'];
 $newArray[$value['id']]['detail'][] = array('order_sn' => $value['order_sn'], 'total' => $value['total']);
}

-1
投票

查看 PHP array_merge 函数。

© www.soinside.com 2019 - 2024. All rights reserved.