0

I have got an array which is similar to this:

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
    )
)

I want rearrange it this way:

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

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

Basically what i want is the cartId will be parent key and attributeId will be sub-key and value will be its respective value and all records will come under one cartId.

Thanks in advance.

4

2 回答 2

2

So that will be:

$result = [];
foreach($array as $item)
{
   $result[$item['cartId']][]=[$item['attributeId']=>$item['value']];
}
于 2013-11-07T08:47:23.683 回答
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
        )

)
于 2013-11-07T09:05:28.453 回答