我有一个像这样的数组
Array
(
[0] => Array
(
[0] => 83
[1] => 82
[2] => 81
)
[1] => Array
(
[0] => 81
[1] => 82
[2] => 83
[3] => 100
[4] => 101
[5] => 102
[6] => 103
[7] => 104
[8] => 105
)
)
我希望删除第一个数组中不等于此数组的任何值
Array
(
[0] => 83
[1] => 82
[2] => 81
)
但我想保持与第一个数组相同的结构。所以我最终会得到像这样的东西
Array
(
[0] => Array
(
[0] => 83
[1] => 82
[2] => 81
)
[1] => Array
(
[0] => 81
[1] => 82
[2] => 83
)
)
实现这一目标的最佳方法是什么?
答案 0 :(得分:4)
$data = array( /* your data you want to check (first big array) */ );
$test = array( 83, 82, 81 );
foreach ( $data as $key => $value ) {
$intersect = array_intersect($value, $test);
if ( $intersect != $test ) {
unset($data[$key]);
} else {
$data[$key] = $intersect;
}
}
答案 1 :(得分:2)
如果$array
是您的起始数组,而$matches
是您要匹配的值数组;
foreach ($array as $key => $subarray) {
foreach ($subarray as $subsubarray) {
foreach ($matches as $match) {
if ($subsubarray == $match) {
$finalarr[$key][] = $subsubarray;
}
}
}
}
$finalarr
将是您想要的结果。
答案 2 :(得分:0)
您始终可以将数组设置为第一个和第二个数组与array_intersect函数的交集。
<?php
$array[1] = array_intersect($array[0], $array[1]);
?>
答案 3 :(得分:0)
$temp = array
(
0 => array
(
0 => 83,
1 => 82,
2 => 81
),
1 => array
(
0 => 81,
1 => 82,
2 => 83,
3 => 100,
4 => 101,
5 => 102,
6 => 103,
7 => 104,
8 => 105
)
);
for($i=0,$tot = count($temp[1]);$i<$tot;$i++)
{
if(!in_array($temp[1][$i],$temp[0]))
{
unset($temp[1][$i]);
}
}