从PHP数组获取逗号分隔的值

时间:2019-05-28 19:31:28

标签: php

我因此有一个数组

$main_array = [

    ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
    ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"]
    ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]

]

我使用foreach来基于tag的值回显一些HTML。像这样

    foreach($main_array as $key => $array) {        
        if ($array['tag'] == "bright") { 
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }

这只会输出与标签“ bright”匹配的“ ned”。但是它也应该输出“ helen”。同样:

    foreach($main_array as $key => $array) {        
        if ($array['tag'] == "wavy") { 
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }

应输出“ james”和“ helen”。我需要什么样的功能才能达到预期的效果?

2 个答案:

答案 0 :(得分:2)

在检查项目列表中的项目时,可以使用explode()将其拆分为多个部分(我使用了", "拆分,因为每个项目似乎也有空格),并且然后使用in_array()检查它是否在列表中...

if (in_array("bright", explode( ", ", $array['tag']))) {

答案 1 :(得分:0)

您不能直接执行此操作,因为它会返回带有字符串值的键。下面是工作代码。

<?php
   $main_array = [

    ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
    ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"],
    ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]

];

foreach($main_array as $key => $array) { 
    $str_arr = explode (", ", $array['tag']);
    foreach ($str_arr as $key2 => $array2) {
        if ($array2 == "wavy") { 
            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
        }
    }
}
?>