将多维多级数组过滤为uniq

时间:2015-06-16 12:48:12

标签: php arrays multidimensional-array

我有下一个问题,我想为uniqe过滤一个多维和多级数组。

一个例子:

<X-PRE-PROCESS cmd="set" data="global_codec_prefs=OPUS,G722,PCMU,PCMA,GSM"/>

之前的数组我想用uniqe值来制作它。

2 个答案:

答案 0 :(得分:1)

我不知道这是否是最快/最短的答案,但下面的代码可能适合您:

#Function to make a multidimensional array unique

function makeUnique(&$array)
{       
    foreach($array as $key => &$value)
    {
        if(is_array($value))
        {   
            makeUnique($value);
            $value = array_unique($value);

        }
    }
    return $array;
}

#Example of your array

$exampleArray = Array(
    'Home'  => Array(
        'Kids' => Array(
            'For sleeping' => Array(
                0 => 'Sleeping Bags',
                1 =>'mattress',
                2 =>'mattress')
                )
        )
    );


#Make the array unique and print the results

makeUnique($exampleArray);
print_r($exampleArray); 

答案 1 :(得分:0)

我已经解决了这个问题。这个问题的解决方案是:

$test = Array
(
    [Home] => Array
        (
            [Kids] => Array
                (
                    [For sleeping] => Array
                        (
                            [0] => Sleeping Bags

                            [1] => mattress

                            [2] => mattress

                            [3] => mattress

                            [4] => Beds

                            [5] => Beds

                            [6] => Beds
[..]

foreach ($test as $key=>$value){
    foreach ($value as $key2 => $value2) {
        foreach ($value2 as $key3=>$value3) {
            $cat[$key][$key2][$key3]= array_unique($value3);
        }

    }
}