PHP - 检查一个数组中的值是否存在于另一个数组多维数组中

时间:2016-06-18 15:21:28

标签: php arrays multidimensional-array

我有以下两个数组。

这是一个平面数组(字符串:$ second_names):

Array ( [0] => Cars [3] => Bikes [8] => Trucks ) //$second_names

我有这个多维数组 - (string:$ premiumCatArraySets):

Array
(
    [0] => Array
        (
            [primary-category] => Automobiles
            [secondary-category] => Cars
            [tertiary-category] => Fiat Punto
        )
[1] => Array
    (
        [primary-category] => Automobiles
        [secondary-category] => Cars
        [tertiary-category] => BMW
    )

[2] => Array
    (
        [primary-category] => Automobiles
        [secondary-category] => Bikes
        [tertiary-category] => Honda
    )

[4] => Array
    (
        [primary-category] => Automobiles
        [secondary-category] => Trucks
        [tertiary-category] => Iveco
    )

[6] => Array
    (
        [primary-category] => Automobiles
        [secondary-category] => Cars
        [tertiary-category] => Mercedes
    )

[9] => Array
    (
        [primary-category] => Automobiles
        [secondary-category] => Cars
        [tertiary-category] => Toyota
    )

我正在尝试使用in_array来查看平面阵列中的值是否存在并输出汽车的品牌。

这就是我试过的

foreach ($second_names as $second_name) {//Vechile type e.g. car, truck, bike
    if(in_array($second_name, $premiumCatArraySets)){
        echo '<h2>'.$second_name.'</h2>';
        foreach ($third_names as $third_name) {// e.g. Fiat, BMW, Toyota
            echo $third_name.'<br/>';
        }
    }
}

if(in_array($second_name, $premiumCatArraySets)){的行似乎没有显示任何内容。

3 个答案:

答案 0 :(得分:2)

如果我的理解是正确的,你必须从第一个阵列中的每辆车的第二个阵列获得车辆品牌。你可以做类似下面的事情。这是一个基本脚本。

nodejs v4.4.5LTS

答案 1 :(得分:1)

尝试

$output = [];
foreach($premiumCatArraySets as $key => $value){    
    if(in_array($value["secondary-category"],$second_names)){
        if(!isset($output[$value["secondary-category"]])){
            $output[$value["secondary-category"]]  = [];
        }        
        $output[$value["secondary-category"]][] = $value["tertiary-category"];
    }
}
foreach($output as $key => $value){ 
    echo '<h2>'.$key."</h2>";
        echo implode(", ",$value)."<br/>";
}

<强>输出

Cars    
Fiat Punto, BMW, Mercedes, Toyota

Bikes    
Honda

Trucks    
Iveco
  

参考:Demo

答案 2 :(得分:1)

使用call_user_func_arrayarray_merge_recursivearray_keysarray_fliparray_intersect_keyimplode函数的解决方案:

// grouping each category preserving the position of each item
$groups = call_user_func_array('array_merge_recursive', $premiumCatArraySets);
foreach ($second_names as $name) {
    $indexes = array_flip(array_keys($groups['secondary-category'], $name));
    echo '<h2>'.$name.'</h2>';
    echo implode(", ", array_intersect_key($groups['tertiary-category'], $indexes)) .'<br/>';
}

输出:

<h2>Cars</h2>Fiat Punto, BMW, Mercedes, Toyota<br/><h2>Bikes</h2>Honda<br/><h2>Trucks</h2>Iveco<br/>