使用php将mysql数据转换为所需格式的json
我有一张有价值观的桌子使用php将mysql数据转换为所需格式的json,php,json,Php,Json,我有一张有价值观的桌子 | CategoryName | ClientName | Phone Number | |--------------------------|------------|--------------| | Mobile repair | XYZ | 90000000 | | Mobile repair | ABC | 91111111 | | Car serv
| CategoryName | ClientName | Phone Number |
|--------------------------|------------|--------------|
| Mobile repair | XYZ | 90000000 |
| Mobile repair | ABC | 91111111 |
| Car service | AZC | 89999999 |
| TV repair | MNB | 88888888 |
| Car service | LLL | 99999999 |
我想要JSON的格式
{
"Mobile Repair" : {"XYZ":"90000000","ABC":"91111111"},
"Car Service" :{ "AZC" : "89999999","LLL":"99999999"},
"TV Repair" :{"MNB","88888888"}
}
但我正在学习格式
{
"Mobile Repair" : {"ABC":"91111111"},
"Car Service" :{ "LLL":"99999999"},
"TV Repair" :{"MNB","88888888"}
}
我的sql查询是
$query = "select S.SpecificCategoryName,A.ClientName,A.PhoneNumber from specificcategories S,clientstable A where A.SpecificCategoryId=S.SpecificCategoryId and A.LocationCode=(Select LocationCode from areas where LocationName='".$location."')";
我将这些值格式化为
for($row = 0; $row < count($result); $row++)
{
$values[$result[$row]['SpecificCategoryName']] = array($result[$row['ClientName']=>$result[$row]['PhoneNumber']);
}
for($row=0;$row$result[$row]['PhoneNumber']);
}
请帮助将JSON编码为上述格式。只需添加
[]
括号,您的数据就不会被覆盖
for($row = 0; $row < count($result); $row++)
{
$category = $result[$row]['SpecificCategoryName'];
$name = $result[$row]['ClientName'] ;
$phone = $result[$row]['PhoneNumber'] ;
$values[$category][$name] = $phone;
}
echo json_encode($values);
for($row=0;$row
您必须将每个列的值作为键附加到数组中:
for($row = 0; $row < count($result); $row++)
{
$cat = $result[$row]['SpecificCategoryName'];
$name = $result[$row]['ClientName'] ;
$phone = $result[$row]['PhoneNumber'] ;
$values[$cat][$name] = $phone;
}
for($row=0;$row感谢上述内容,现在数据没有被覆盖,但我得到的格式是{“移动维修”:[{“XYZ”:“90000000”,“ABC”:“91111111”}],“汽车服务”:[{“AZC”:“89999999”,“LLL”:“99999999”}],“电视维修”:[{“MNB”,“88888888888”}}}}而我想要的格式是{“移动维修”:{“XYZ”:“90000000”,“ABC”:“91111111”},“汽车服务”:{“AZC”:“899999999”,“LLL”:“9999999”},“电视维修”:{“MNB”,“88888888”}好的,现在它将是你所期望的,请在帖子中添加一些上下文
foreach ($results as $row)
{
$cat = $row['SpecificCategoryName'];
$name = $row['ClientName'] ;
$phone = $row['PhoneNumber'] ;
$values[$cat][$name] = $phone;
}
for($row=0; $row<count($result); $row++) {
$values[$result[$row]['SpecificCategoryName']][$result[$row]['ClientName']] = $result[$row]['PhoneNumber'];
}