如何在数组上合并键数组

时间:2011-04-15 05:51:32

标签: php arrays multidimensional-array

我遇到了一个问题(对我来说很重要):(

好的,我有一些像...

的数组
    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
                )
            )
        )

    [2] => 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 ...我应该为这种情况做什么方法?

我尝试在谷歌和这里搜索...但我不知道关键字>。<

非常感谢之前:)

关于,斯蒂奇

4 个答案:

答案 0 :(得分: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'],
  );
}

答案 1 :(得分: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进行配对,因此将其作为键以及与其关联的所有数据作为值是明智的。没有必要iddetail

答案 2 :(得分: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']);
}

答案 3 :(得分:-1)

查看PHP array_merge函数。