我有一个像这样的数组
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
)
)
实现这一目标的最佳方法是什么?
$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;
}
}
如果$array
是您的起始数组,$matches
是您想要匹配的值的数组;
foreach ($array as $key => $subarray) {
foreach ($subarray as $subsubarray) {
foreach ($matches as $match) {
if ($subsubarray == $match) {
$finalarr[$key][] = $subsubarray;
}
}
}
}
$finalarr
将是您想要的结果。
可以使用array_intersect函数将数组设置为第一个和第二个数组的交集。
<?php
$array[1] = array_intersect($array[0], $array[1]);
?>
$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]);
}
}