将数据库结果集数组绑定到php中的逗号分隔字符串

时间:2017-11-14 11:35:47

标签: php string

我有一个数组,它是这样的数据库查询的输出(采用JSON格式):

[  
 {  
  "id":1,
  "name":"Category group sidebar",
  "location":"category_group_sidebar",
  "width":250,
  "height":225
  },
{  
  "id":2,
  "name":"Category sidebar",
  "location":"category_sidebar",
  "width":250,
  "height":225
  } 
]

我希望此结果附加以下字符串,结果以逗号分隔,如下所示:

The ad space names are Category group sidebar,Category sidebar and the dimensions are 250,225

3 个答案:

答案 0 :(得分:1)

试试这个(不能测试):

$json = json_decode($json_data, true);

$insert = "";

foreach ($json as $data) {
  $insert .= $data['name'] . ",";
}

$insert = rtrim($insert, ",");

$text = "The ad space names are {$insert} and the dimensions are 250,225"

新回复:

$json = json_decode($json_data, true);

$insert = "";

foreach ($json as $data) {
  $insert .= $data['name'] . " with dimension " . $data['width'] . "*" . $data['height'] . ",";
}

$insert = rtrim($insert, ",");

$text = "Ad spaces are, {$insert}"

答案 1 :(得分:0)

这将获取在每个数组的数组中找到的所有属性,按空间连接内部数组,由array_map创建的外部数组将使用逗号连接。

$jsonData = json_decode($yourJsonData, true);
$output = implode(", ", array_map($jsonData, function(item) { return implode(" ", $item); });

答案 2 :(得分:0)

$array = json_decode($json_array);
foreach ($array as $key => $value) {
 if(!isset($str)){
   $str= $value['name']; 
 }else{
   $str= ",".$value['name'];
 }
}
$string = "The ad space names are ".$str" and the dimensions are 250,225";
echo $string;