array_unique在php中,数组中有子数组


array_unique in php with subarray in array

如何对此数组使用array_unique函数`

$mon  = array('9:00AM - 11:00AM','1:00pm-6pm');
$tue  = array('8:00AM - 11:00AM','12:00pm-6pm');
$wed  = array('9:00AM - 11:00AM','1:00pm-6pm');
$thu  = array('9:00AM - 11:00AM','1:00pm-6pm');
$fri  = array('9:00AM - 12:00PM','1:00pm-6pm');
$sat  = array('9:00AM - 7:00PM');
$sun  = array('9:00AM - 12:00AM','1:00pm-6pm');
$a=array($mon , $tue , $wed , $thu , $fri , $sat , $sun);
print_r(array_unique($a));

您也可以使用此解决方案:

$schedule = array(
    array('9:00AM - 11:00AM','1:00pm-6pm'),
    array('8:00AM - 11:00AM','12:00pm-6pm'),
    array('9:00AM - 11:00AM','1:00pm-6pm'),
    array('9:00AM - 11:00AM','1:00pm-6pm'),
    array('9:00AM - 12:00PM','1:00pm-6pm'),
    array('9:00AM - 7:00PM'),
    array('9:00AM - 12:00AM','1:00pm-6pm'),
);
$schedule = array_map(function ($item) {
    return json_encode($item);
}, $schedule);
// use array_flip to switch keys and values. By doing it the duplicates will be removed    
$json = '[' . implode(',', array_keys(array_flip($schedule))) . ']';
$schedule = json_decode($json);
var_dump($schedule);

您必须为多维数组编写自定义函数,请参阅下面的功能

function unique_multidim_array($array, $key){
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val){
    if(!in_array($val[$key],$key_array)){
        $key_array[$i] = $val[$key];
        $temp_array[$i] = $val;
    }
    $i++;
}
return $temp_array; }

现在,在代码的任何位置调用此函数

 $details = unique_multidim_array($details,'id');

如果你的情况下,你必须通过密钥作为0或1像

$a=unique_multidim_array($a,0);

对于array_unique(),PHP手册PHP手册中说

两个元素被认为是相等的,当且仅当(字符串)$elem1==(字符串)$elem2时,即当字符串表示相同时,第一个元素将被使用

因此,在内部,输入数组的每个元素在比较之前都被强制转换为字符串。当您将子数组作为元素时,将它们强制转换为字符串将输出一个";数组到字符串的转换";通知并返回一个无用的结果:

var_dump((string)['foo', 'bar']); // string(5) "Array"

幸运的是,构建array_unique()的替代品很容易:

function uniquify(array $arr) {
    return array_reduce(
        $arr,
        function ($carry, $item) {
            if (!in_array($item, $carry)) {
                $carry[] = $item;
            }
            return $carry;
        },
        []
    );
}