将php foreach放入带空格的单变量逗号分隔字符串

时间:2018-09-17 07:08:58

标签: php codeigniter

将php foreach放入带有空格和特殊字符的单变量逗号分隔的字符串中。

$fruit = $this->db->query("SELECT * FROM tblFruitTrees") 

foreach($fruit as $fruits) {
 $result .= '{"value":"'.$fruits.'"}';
}

输出应为:

$ result =  {"value":"+red apple"},{"value":"+yellow banana"},{"value":"+green mango"}

1 个答案:

答案 0 :(得分:1)

我认为您想要的是implode

$fruits = array("+red apple", "+yellow banana", "+green mango");
$result = '{"value":"' . implode('"}, {"value":"', $fruits) . '"}';
echo $result;

输出:

{"value":"+red apple"}, {"value":"+yellow banana"}, {"value":"+green mango"}

如果+实际上不在水果值中,只需将其添加到爆破中:

$fruits = array("red apple", "yellow banana", "green mango");
$result = '{"value":"+' . implode('"}, {"value":"+', $fruits) . '"}';
echo $result;

输出:

{"value":"+red apple"}, {"value":"+yellow banana"}, {"value":"+green mango"}

这是使用json_encode的解决方案:

$fruits = array("+red apple", "+yellow banana", "+green mango");
$result = implode(',', array_map(function ($f) { return json_encode(array('value' => $f)); }, $fruits));
echo $result;

输出:

{"value":"+red apple"},{"value":"+yellow banana"},{"value":"+green mango"}