当数组具有子数组时,array_intersect引发错误 [英] array_intersect throws errors when arrays have sub-arrays

查看:80
本文介绍了当数组具有子数组时,array_intersect引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用array_intersect比较两个数组.

I'm trying to use array_intersect to compare two arrays of arrays.

$start[]=array(
        'id'=>1,
        'name'=>'Up',
        'action'=>'up'
);
$start[]=array(
        'id'=>3,
        'name'=>'Down',
        'action'=>'down'
);
$start[]=array(
        'id'=>5,
        'name'=>'Left',
        'action'=>'left'
);




$end[]=array(
        'id'=>1,
        'name'=>'Up',
        'action'=>'up'
);
$end[]=array(
        'id'=>9,
        'name'=>'Up',
        'action'=>'up'
);

$result=array_intersect($start,$end);

但是,我总是收到通知消息:

However, I always get the notice message:

注意:第 xyz

实际上并没有进行比较.

And the comparison doesn't actually occur.

比较两个数组而不重新发明轮子或得到过于复杂的东西的最佳方法是什么?

What is the best way to compare the two arrays without reinventing the wheel or arriving at something overly complex?

推荐答案

其他地方建议使用array_map并进行序列化.我最终想到了这一点-这肯定比嵌套和递归要容易得多,并且在尝试基本上重写array_intersect函数时惨遭失败.

Someone else elsewhere suggested array_map and serialize. I ended up coming up with this--which is certainly much easier than nesting and recursion and failing miserably in an attempt to basically rewrite the array_intersect function.

echo '<pre>';

$start[]=array(
        'id'=>1,
        'name'=>'Up',
        'action'=>'up'
);
$start[]=array(
        'id'=>3,
        'name'=>'Down',
        'action'=>'down'
);
$start[]=array(
        'id'=>5,
        'name'=>'Left',
        'action'=>'left'
);
$start[]=array(
        'id'=>2,
        'name'=>'Left',
        'action'=>'left'
);





$end[]=array(
        'name'=>'Up',
        'id'=>1,

        'action'=>'up'
);
$end[]=array(
        'id'=>8,
        'name'=>'Right',
        'action'=>'Right'
);




function serialize_array_values($arr){
    foreach($arr as $key=>$val){
        sort($val);
        $arr[$key]=serialize($val);
    }

    return $arr;
}




$result = array_map("unserialize", array_intersect(serialize_array_values($start),serialize_array_values($end)));

echo "\n\n\n";
echo var_dump($result);


echo '</pre>';

这篇关于当数组具有子数组时,array_intersect引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆