从 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"]


]

我使用 aforeach根据 的值回显一些 HTML tag。像这样的东西


    foreach($main_array as $key => $array) {        

        if ($array['tag'] == "bright") { 

            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';

        }

    }

这只会输出“ned”作为匹配标签“bright”。但它也应该输出“海伦”。相似地:


    foreach($main_array as $key => $array) {        

        if ($array['tag'] == "wavy") { 

            echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';

        }

    }

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


慕斯王
浏览 294回答 2
2回答

互换的青春

在检查项目列表中的项目时,您可以使用explode()将其拆分为多个部分(我使用了 split by", "因为每个项目似乎也有一个空格)然后用于in_array()检查它是否在列表中...if&nbsp;(in_array("bright",&nbsp;explode(&nbsp;",&nbsp;",&nbsp;$array['tag'])))&nbsp;{

扬帆大鱼

您不能直接执行此操作,因为它返回带有字符串值的键。下面是工作代码。<?php&nbsp; &nbsp;$main_array = [&nbsp; &nbsp; ["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],&nbsp; &nbsp; ["image" => "ned.jpg", "name" => "ned", "tag" => "bright"],&nbsp; &nbsp; ["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]];foreach($main_array as $key => $array) {&nbsp;&nbsp; &nbsp; $str_arr = explode (", ", $array['tag']);&nbsp; &nbsp; foreach ($str_arr as $key2 => $array2) {&nbsp; &nbsp; &nbsp; &nbsp; if ($array2 == "wavy") {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}?>
打开App,查看更多内容
随时随地看视频慕课网APP