[英]Using array_filter to filter multidimensional array with another array
I have two arrays, the second is multidimensional. 我有两个数组,第二个是多维数组。 I'm trying to return a third array where the service_id in Array2 match the values in Array1. 我试图返回第三个数组,其中Array2中的service_id与Array1中的值匹配。
Array1
(
[0] => 158
[1] => 162
)
Array2
(
[localhost] => Array
(
[0] => Array
(
[host_name] => localhost
[current_state] => 0
[service_id] => 158
)
[1] => Array
(
[host_name] => localhost
[current_state] => 0
[service_id] => 159
)
)
[192.168.0.43] => Array
(
[0] => Array
(
[host_name] => 192.168.0.43
[current_state] => 0
[service_id] => 168
)
[1] => Array
(
[host_name] => 192.168.0.43
[current_state] => 1
[service_id] => 162
)
)
)
So Array3 should be: 因此,Array3应该是:
Array3
(
[localhost] => Array
(
[0] => Array
(
[host_name] => localhost
[current_state] => 0
[service_id] => 158
)
[192.168.0.43] => Array
(
[0] => Array
(
[host_name] => 192.168.0.43
[current_state] => 0
[service_id] => 162
)
)
)
Here is what I have so far, but it doesn't appear to be filtering the entire array. 这是我到目前为止的内容,但似乎并没有过滤整个数组。
$Array3= array_filter($Array2, function ($value) use ($Array1) {
return in_array(array_shift($value)['service_id'], $Array1);
});
Am I close here, What am I missing? 我在这里关闭吗,我想念什么?
I think it's because you want to filer at a second depth that it needs to loop across the first level and then filter the second level (think that sort of makes sense). 我认为这是因为您想在第二个层次进行过滤,所以它需要遍历第一层,然后过滤第二层(以此类推)。
So this code uses array_map()
to loop over the host level of the array ( localhost
and 192.168.0.43
) and then uses array_filter()
within this. 因此,此代码使用array_map()
遍历数组的主机级别( localhost
和192.168.0.43
),然后在其中使用array_filter()
。 Have to use use()
to pass the lookup array into each level of the function 必须使用use()
将查找数组传递到函数的每个级别
$array3 = array_map(function($data) use ($Array1)
{ return array_filter($data, function($sub) use ($Array1)
{ return in_array($sub["service_id"], $Array1); });
}, $Array2);
print_r($array3);
prints... 打印...
Array
(
[localhost] => Array
(
[0] => Array
(
[host_name] => localhost
[current_state] => 0
[service_id] => 158
)
)
[192.168.0.43] => Array
(
[1] => Array
(
[host_name] => 192.168.0.43
[current_state] => 1
[service_id] => 162
)
)
)
So below should be what you need to achieve $Array3 : 因此,下面应该是实现$ Array3所需要的:
$Array3 = array(array($Array2[0][0], $Array2[0][1], $Array1[0]), array($Array2[1][0],
$Array2[1][1], $Array1[1]));
However to achieve this more dynamically, you'd want to use something like : 但是,要更动态地实现此目的,您需要使用类似:
$Array3 = array();
for($i = 0; $i < $Array2[0].length; $i++){
array_push($Array3, array($Array2[$i][0], $Array2[$i][1], $Array1[$i]));
}
var_dump($Array3) // For debug only.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.