繁体   English   中英

关联数组:如何消除重复项?

[英]Associative arrays: how to get rid of duplicates?

我有一个数组:

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

$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM