0

我有一个数组:

Array
(
    [0] => Array
        (
            [attribute_name] => Appliances
            [attribute_value] => Washer
        )

    [1] => Array
        (
            [attribute_name] => Appliances
            [attribute_value] => Dryer
        )

    [2] => Array
        (
            [attribute_name] => Appliances
            [attribute_value] => Dishwasher
        )

    [3] => Array
        (
            [attribute_name] => Appliances
            [attribute_value] => Microwave
        )

    [4] => Array
        (
            [attribute_name] => Console
            [attribute_value] => Xbox360
        )

    [5] => Array
        (
            [attribute_name] => Console
            [attribute_value] => PS3
        )
)

我想生产:

Array
(
    [0] => Array
        (
            [attribute_name] => Appliances
            [attribute_value] => Washer, Dryer, Dishwasher, Microwave
        )

    [1] => Array
        (
            [attribute_name] => Console
            [attribute_value] => Xbox360, PS3
        )
)

这是如何在 PHP 中实现的?

这是我基于@andrewtweber 的原始解决方案的最终代码:

http://codepad.org/E4WFnkbc

4

1 回答 1

4
$new_arr = array();

foreach( $arr as $data ) {
    if( !isset($new_arr[$data['attribute_name']]) ) {
        $new_arr[$data['attribute_name']] = array();
    }
    $new_arr[$data['attribute_name']][] = $data['attribute_value'];
}

这会给你

array( 'Appliances' => array( 'Washer', 'Dryer', 'Dishwasher' ) );

http://codepad.org/m6l3je0H

于 2012-06-27T23:40:45.320 回答