简体   繁体   中英

Getting comma separated values from PHP array

I have an array thusly

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

]

I use a foreach to echo some HTML based on the value of tag . Something like this

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

This only outputs "ned" as matching the tag "bright". But it should output "helen" too. Similarly:

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

Should output "james" and "helen". What kind of function do I need to achieve the desired result?

检查项目列表中的项目时,可以使用explode()将其拆分为多个部分(我使用过", "分隔", "因为每个项目似乎也有空格),然后使用in_array()进行检查如果在列表中...

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

You cant do it directly, because it return key with values in string. Below are the working code.

<?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>';
        }
    }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM