日期:2014-05-17  浏览次数:20731 次

这样的二维数组合并并去掉重复值,该怎么做
这样的二维数组合并并去掉重复值(attr_id,attr_name,attr_value三个字段都相同的则保留一个去除一个)
PHP code

Array
(
    [0] => Array
        (
            [attr_id] => 16950
            [attr_name] => 台式机CPU品牌
            [attr_value] => AMD

        )

    [1] => Array
        (
            [attr_id] => 16951
            [attr_name] => 台式机操作系统
            [attr_value] => Linux

        )

)

Array
(
    [0] => Array
        (
            [attr_id] => 16955
            [attr_name] => 售后服务
            [attr_value] => 一年
        )

)




------解决方案--------------------
function array_multi_unique($ar) {
$ar = array_map('serialize', $ar);
$ar = array_unique($ar);
return array_map('unserialize', $ar);
}

print_r( array_multi_unique($a) );
------解决方案--------------------
在唠叨老大的基础上改改
PHP code


<?php

$new = Array
(
    '0' => Array
        (
            'attr_id' => '16950',
            'attr_name' => '台式机CPU品牌',
            'attr_value' => 'AMD',
            'attr_type' => 1,
            'belong' => 'goods_sku'
        ),
    '1' => Array
        (
            'attr_id' => '16951',
            'attr_name' => '台式机操作系统',
            'attr_value' => 'Linux',
            'attr_type' => 2,
            'belong' => 'goods_sku'
        ),
    '2' => Array
        (
            'attr_id' => '16955',
            'attr_name' => '售后服务',
            'attr_value' => '一年',
            'attr_type' => 2,
            'belong' => 'goods_sku'
        ),
    '3' => Array
        (
            'attr_id' => '16950',
            'attr_name' => '台式机CPU品牌',
            'attr_value' => 'AMD',
            'attr_type' => 1,
            'belong' => 'goods'
        )
);

// 老大的基础上改改
function array_multi_unique($ar, $filter=array()) {

    if(!empty($filter)) {
        $_v = array_fill_keys($filter, ' ');
        $_ar = array();
        foreach($ar as $k => $v) {
            $_ar[$k] = array_intersect_key($v, $_v);
        }
    } else {
        $_ar = $ar;
    }

    $_ar = array_map('serialize', $_ar);
    $_ar = array_unique($_ar);
    $_ar = array_map('unserialize', $_ar);

    if(!empty($filter)) {        
        return array_intersect_key($ar, $_ar);
    } else {
        return $_ar;
    }
}

print_r(array_multi_unique($new, array('attr_id', 'attr_name', 'attr_value')));