Foreach项目(如果项目来自类型/类别之一)

时间:2019-02-12 01:13:12

标签: php

我正在寻找从php数组中键入类型为“键”的每个项目。 显示类型之一为type-2的所有项目。

谢谢

 <?php $gallery = [];
       $gallery [1] = [
       "Name" => "Three Full Length Mirrors",
       "Description" => "Three mirrors with silver aluminum profile. ",
       "image" => "full-mirror.jpg",
       "type" => [
                "type-1",
                "type-2",
                "type-3"
            ]
        ];
    ?>

2 个答案:

答案 0 :(得分:0)

您可以使用array_filter对数组进行预过滤,但是将测试放入foreach循环中也很容易:

foreach ($gallery as $g) {
    if (!in_array('type-2', $g['type'])) continue;
    // rest of code
}

答案 1 :(得分:0)

<?php 


$result = array_filter($gallaries, function($gallery){
    // If below is true element stays, the false cases get removed from array
    return in_array('type-2',$gallery['type'])
});