数组重新排列在PHP中

时间:2013-11-07 08:43:19

标签: php arrays

我有一个与此类似的数组:

Array
(
[0] => Array
    (
        [cartId] => 51
        [attributeId] => 171
        [Value] => 34
        [quantity] => 1
    )

[1] => Array
    (
        [cartId] => 51
        [attributeId] => 170
        [Value] => Adult
        [quantity] => 1
    )

[2] => Array
    (
        [cartId] => 52
        [attributeId] => 171
        [Value] => 36
        [quantity] => 1
    )

[3] => Array
    (
        [cartId] => 52
        [attributeId] => 170
        [Value] => Adult
        [quantity] => 1
    )
)

我想以这种方式重新排列:

Array
(
[51] => Array
    (
        [171] => 34
        [170] => Adult
    )

[52] => Array
    (
        [171] => 36
        [170] => Adult
    ) 
)

基本上我想要的是cartId将是父键,attributeId将是子键,value将是其各自的值,所有记录将在一个cartId下。

提前致谢。

2 个答案:

答案 0 :(得分:2)

那将是:

$result = [];
foreach($array as $item)
{
   $result[$item['cartId']][]=[$item['attributeId']=>$item['value']];
}

答案 1 :(得分:1)

嗯..这很简单:

PHP代码:

<?php 
$data = array();
$result = array();

$data[] = array('cartId'=>51,'attributeId'=>171,'Value'=>34,'quantity'=>1);
$data[] = array('cartId'=>51,'attributeId'=>170,'Value'=>'Adult','quantity'=>1);
$data[] = array('cartId'=>52,'attributeId'=>171,'Value'=>36,'quantity'=>1);
$data[] = array('cartId'=>52,'attributeId'=>170,'Value'=>'Adult','quantity'=>1);
$data[] = array('cartId'=>53,'attributeId'=>171,'Value'=>45,'quantity'=>1);
$data[] = array('cartId'=>53,'attributeId'=>170,'Value'=>'Adult','quantity'=>1);

foreach($data as $item)
{
   $result[$item['cartId']][$item['attributeId']]=$item['Value'];
}

echo "<pre>";
print_r($result);
echo "</pre>";

<强>输出:

Array
(
    [51] => Array
        (
            [171] => 34
            [170] => Adult
        )

    [52] => Array
        (
            [171] => 36
            [170] => Adult
        )

    [53] => Array
        (
            [171] => 45
            [170] => Adult
        )

)