簡體   English   中英

使用array_filter過濾多維數組

[英]Using array_filter to filter multidimensional array

我有兩個數組,第二個是多維數組。 我試圖返回第三個數組,其中Array2中的host_id與Array1中的值匹配。

Array1 
(
    [0] => 146
    [1] => 173
)

Array2
(
    'localhost' => (
        '0' => (
            'host_id' => 146
        ),
    ),
    '192.168.0.43' => (
        '1' => (
            'host_id' => 160
        ),
    ),
    '192.168.0.38' => (
        '2' => (
            'host_id' => 173
        )
    )
)

因此,Array3應該是:

    Array3
    (
        [localhost] => Array
            '0' => (
                'host_id' => 146
            ),

        [192.168.0.38] => Array
            '0' => (
                'host_id' => 173
            ),

    )

我已經嘗試過了,但是只返回了最后一個匹配的host_id。

foreach ($Array1 as $value) {   

    $filtered_hosts = array_filter($Array2, function ($host) use ($value) {

        return in_array($host['host_id'], $host_id);
    });
}

我想念什么?

您可以只使用array_filter而不使用foreach

將第一個數組傳遞給use($array1)並使用in_array來檢查'host_id'的值是否存在。

$array1 = [
  146,
  173
];

$array2 = [
    'localhost' => [
        'host_id' => 146
    ],
    '192.168.0.43' => [
        'host_id' => 160
    ],
    '192.168.0.38' => [
        'host_id' => 173
    ]
];

$filtered_hosts = array_filter($array2, function($x) use ($array1) {
    return in_array($x['host_id'], $array1);
});


print_r($filtered_hosts);

演示

更新

對於更新的數據結構,您可以從子數組中獲得第一項,例如reset

$filtered_hosts = array_filter($array2, function ($x) use ($array1) {
    return in_array(reset($x)['host_id'], $array1);
});

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM