php用foreach遍历数据表,怎么去掉最后的逗号?

foreach ($res as $row) {
echo '"' . $row[1] . '":"' . $row[2] . '",';
}

//----

"a":"1",
"b":"2",
"c":"3",
"d":"4",


echo implode(',',array_map(function(){
return '"' . $row[1] . '":"' . $row[2] . '"';
},$res))

你是要返回json格式的吧,这种方法输出兼容性不好,如果数据里面包含了双引号,输出的格式就乱了。

输出json最好用json_encode函数

$data=array();
foreach ($res as $row) {
    $data[$row[1]]= $row[2] ;
}
echo json_encode($data);

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答