PHP - 使用另一个数组从多维数组中获取值

PHP - getting the value from the multidimensional array using another array

我有两个数组:

$mainArray = array(
        ['id' => 1, 'name' => 'test'],
        ['id' => 2, 'name' => 'news'],
        ['id' => 3, 'name' => 'foo'],
        ['id' => 4, 'name' => 'bar']...
        );

$array = array(1,2,5,6,7);

我需要检查 $mainArray 中的 id 是否包含在 $array 中,如果包含它需要打印名称。我怎样才能做到这一点?

简单!

foreach($mainArray as $arr) {
    if(in_array($arr['id'], $array)) {
        echo $arr['id'];
    }
}

这应该适合你:

(使用此解决方案,您有一个数组,其中 idkeynamevalue

<?php

    $mainArray = array(
                    ['id' => 1, 'name' => 'test'],
                    ['id' => 2, 'name' => 'news'],
                    ['id' => 3, 'name' => 'foo'],
                    ['id' => 4, 'name' => 'bar']
                );

    $array = array(1,2,5,6,7);
    $result = array();

    foreach($mainArray as $k => $v)
        $result[$v["id"]] = (array_intersect($mainArray[$k], $array) ? $mainArray[$k]["name"] : "");

    $result = array_filter($result);
    print_r($result);

?>

输出:

Array ( [1] => test [2] => news )

并且您可以轻松地遍历数组并打印出所有内容,如下所示:

array_walk($result, function($value, $key) { 
    echo "Key: $key Value: $value <br />";
});

//OR

foreach($result as $key => $value)
    echo "Key: $key Value: $value <br />";

输出:

Key: 1 Value: test 
Key: 2 Value: news