`json_encode`无法使用explode

时间:2016-01-27 11:17:16

标签: php

我有一个包含以逗号分隔的数字的字符串。即,1,2,3,6...。我已经使用explode删除了逗号。现在我想匹配数据库中的相应值。

我的代码是,

$color = "1,2,3,9,5";
$color_split = explode(",", $color);

foreach($color_split as $item)
{
    $select_color = "SELECT * FROM tbl_product_color WHERE color_id = '$item'";
    $select_color_q = mysqli_query($c, $select_color) or die(mysqli_error($c));
    $length =   mysqli_num_rows($select_color_q);

    if($length > 0)
    {
        while($select_color_r = mysqli_fetch_object($select_color_q))
        {
            $var[] = $select_color_r;
        }
        $var = json_encode($var);
        echo '{"color_list":'.$var.'}';
    }
    else
    {
        $arr    =   array('status'=>"notfound");
        echo '{"color_list":['.json_encode($arr).']}';
    }
}

现在输出是,

{"color_list":[{"color_id":"1","color_name":"White","color_code":"#f2f2f2"}]}

and one error,

Fatal error: [] operator not supported for strings in C:\wamp\www\jithin\get_color.php on line 18

第18行包含$var[] = $select_color_r;

我需要的输出是,

{"color_list":[{"color_id":"1","color_name":"White","color_code":"#f2f2f2"},{"color_id":"2","color_name":"Black","color_code":"#000000"},{"color_id":"3","color_name":"Red","color_code":"#F000000"},...]}

2 个答案:

答案 0 :(得分:2)

您不需要在此使用foreachexplode,只需更新MySql查询,code就像

一样
$color = "1,2,3,9,5";
$select_color = "SELECT * FROM tbl_product_color WHERE color_id IN ($color)";
$select_color_q = mysqli_query($c, $select_color) or die(mysqli_error($c));
$arr['color_list'] = array();
if(mysqli_num_rows($select_color_q) > 0)
    {
        while($select_color_r = mysqli_fetch_object($select_color_q))
        {
            $var[] = $select_color_r;
        }

    }else{
        $var = array('status'=>"notfound");
    }

$arr['color_list'] = $var;
echo json_encode($arr);

答案 1 :(得分:1)

您在此处将$var设置为字符串:

 $var = json_encode($var);

但是在foreach的下一步中,您希望将$va r用作数组。

 $var[] = $select_color_r;

只需删除以下行:

    $var = json_encode($var);

并更改此行:

echo '{"color_list":'.$var.'}';

echo '{"color_list":'.json_encode($var);.'}';