比较两个关联数组并用匹配的数组创建一个新数组,PHP
我有这两个数组:
$arr1=array( array("id" => 8, "name" => "test1"),
array("id" => 4, "name" => "test2"),
array("id" => 3, "name" => "test3")
);
$arr2=array( array("id" => 3),
array("id" => 4)
);
如何从 $arr1 中“提取”数组(其中 id 在 $arr2 中具有相同的值)到一个新数组中,并将提取的数组也保留在新数组中,而不考虑关键顺序?
我正在寻找的输出应该是:
$arr3=array(
array("id" => 8, "name" => "test1")
);
$arr4=array( array("id" => 4, "name" => "test2"),
array("id" => 3, "name" => "test3")
);
谢谢
I have this two arrays:
$arr1=array( array("id" => 8, "name" => "test1"),
array("id" => 4, "name" => "test2"),
array("id" => 3, "name" => "test3")
);
$arr2=array( array("id" => 3),
array("id" => 4)
);
How can i "extract" arrays from $arr1, where id have same value in $arr2, into a new array and leave the extracted array also in a new array, without taking into account key orders?
The output i am looking for should be:
$arr3=array(
array("id" => 8, "name" => "test1")
);
$arr4=array( array("id" => 4, "name" => "test2"),
array("id" => 3, "name" => "test3")
);
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我确信有一些现成的神奇数组函数可以处理这个问题,但这是一个基本示例:
输出将与您想要的相同。实例:
I'm sure there's some ready made magical array functions that can handle this, but here's a basic example:
The output will be the same as the one you desired. Live example:
您可以使用
array_udiff()
和array_uintersect()
具有自定义比较函数。我想这最终可能会比其他答案慢,因为这将遍历数组两次。
You can use
array_udiff()
andarray_uintersect()
with a custom comparison function.I guess this may end up being slower than the other answer, as this will be going over the arrays twice.