为特定的相同键创建单独的数组

时间:2014-07-26 06:30:02

标签: php arrays

我有一个如下所示的数组,我想转换这个数组,也就是说,我想通过order_id创建一个单独的数组。

启动数组:

Array
(
    [0] => Array
        (
            [order_id] => 2
            [product_id] => 2
            [product_name] => Product2
            [o_qty] => 5.00
            [d_qty] => 
        )

    [1] => Array
        (
            [order_id] => 2
            [product_id] => 3
            [product_name] => Product 1 Category 2
            [o_qty] => 5.00
            [d_qty] => 54.00
        )

    [2] => Array
        (
            [order_id] => 1
            [product_id] => 4
            [product_name] => Product 2 category 2
            [o_qty] => 1.00
            [d_qty] => 2.00
        )

    [3] => Array
        (
            [order_id] => 3
            [product_id] => 6
            [product_name] => product_name
            [o_qty] => 
            [d_qty] => 1.00
        )

    [4] => Array
        (
            [order_id] => 2
            [product_id] => 7
            [product_name] => afdasdf
            [o_qty] => 3.00
            [d_qty] => 1.00
        )

)

转换后的预期输出就像是,

Array
(
[2] =>Array( 
    [0] => Array
        (
            [product_id] => 2
            [product_name] => Product2
            [o_qty] => 5.00
            [d_qty] => 
        )

    [1] => Array
        (
            [product_id] => 3
            [product_name] => Product 1 Category 2
            [o_qty] => 5.00
            [d_qty] => 54.00
        )
   [3] => Array
        (

            [product_id] => 7
            [product_name] => afdasdf
            [o_qty] => 3.00
            [d_qty] => 1.00
        )
     )
[1] => Array
        (
            [product_id] => 4
            [product_name] => Product 2 category 2
            [o_qty] => 1.00
            [d_qty] => 2.00
        )

[3] => Array
        (
            [product_id] => 6
            [product_name] => product_name
            [o_qty] => 
            [d_qty] => 1.00
        )
)

1 个答案:

答案 0 :(得分:2)

使用foreach循环构建新数组

$output = array();
foreach ($arr as $v) {
    $k = $v['order_id'];
    unset($v['order_id']);
    $output[$k][] = $v;
}