给出以下数组: -
$array = Array(
[key1] = Array
(
[0] => 5
[1] => Array(1,2,3)
)
[key2] = Array
(
[0] => 15
[1] => Array(11,32,3,5)
)
...
)
如何过滤$array[key][1]
等于给定Array(1,2,3)
的所有元素?
答案 0 :(得分:1)
您可以这样使用数组过滤器:
$array = Array(
'key1' => Array
(5,Array(1,2,3)),
'key2' => Array
(15,Array(11,32,3,5))
);
function changeArray($array, $parameter) {
return array_filter($array, function($v) use ($parameter) {
return $v[1] == $parameter;
});
}
var_dump(changeArray($array, Array(1,2,3)));
?>
答案 1 :(得分:1)
PHP的array_filter()
函数很容易阅读:
<?php
$input = [
'key1' => [
0 => 5,
1 => [1,2,3]
],
'key2' => [
0 => 15,
1 => [11,32,3,5]
],
'key3' => [
0 => 15,
1 => [1,2,3]
],
'key4' => [
0 => 151,
1 => [11,32,3,5]
],
'key5' => [
0 => 15,
1 => [1,2,3,4,5]
]
];
$pattern = [1,2,3];
$output = array_filter($input, function($subject) use ($pattern) {
return $pattern === $subject[1];
});
print_r(array_keys($output));
上述代码的输出显然是:
Array
(
[0] => key1
[1] => key3
)