我正在尝试提供特定尺寸储物柜的数量。我的 SQL 语句是:
$sql = "SELECT Concat(`Height`, 'x', `Width`, 'x', `Depth`) as Locker, count(*) from lockers GROUP BY `Height`, `Width`, `Depth` ";
行循环中的 var_dump 给出了以下内容(可能还有更多行):
array(2) { ["Locker"]=> string(8) "15x30x45" ["count(*)"]=> int(6) }
array(2) { ["Locker"]=> string(8) "45x30x45" ["count(*)"]=> int(4) }
我想获取如下所示的 JSON 字符串:
{
"SizeList": {
"15x30x45": 6
"45x30x45": 4
}
}
我尝试了很多不同的方法(包括将其转换为对象,但我无法获取大小的值作为索引。例如,我得到了以下的不同变体:
[0]=> string(31) "{"Locker":"15x30x45","count(*)":6}"
[1]=> string(31) "{"Locker":"45x30x45","count(*)":4}"
感谢任何帮助...
最佳答案
您可以像这样手动创建对象:
$sizeList = new stdClass();
foreach ($results as $row) {
$sizeList->{$row['Locker']} = $row['count(*)'];
}
echo json_encode(array('SizeList' => $sizeList));
关于php - 如何仅在 PHP 中将数据库行转换为 JSON 值字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53685125/