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



我有一个数组,它是像这样的数据库查询的输出(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

试试这个(无法测试(:

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

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

$jsonData = json_decode($yourJsonData, true);
$output = implode(", ", array_map($jsonData, function(item) { return implode(" ", $item); });
$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;

最新更新