我有一个值为
的表格| 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']);
}
请帮助以上述格式编码JSON。
答案 0 :(得分:2)
您必须将每个列的值附加到数组中作为键:
for($row = 0; $row < count($result); $row++)
{
$cat = $result[$row]['SpecificCategoryName'];
$name = $result[$row]['ClientName'] ;
$phone = $result[$row]['PhoneNumber'] ;
$values[$cat][$name] = $phone;
}
或foreach
:
foreach ($results as $row)
{
$cat = $row['SpecificCategoryName'];
$name = $row['ClientName'] ;
$phone = $row['PhoneNumber'] ;
$values[$cat][$name] = $phone;
}
答案 1 :(得分:0)
只需添加[]
括号,您的数据就不会被覆盖。
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);
答案 2 :(得分:0)
for($row=0; $row<count($result); $row++) {
$values[$result[$row]['SpecificCategoryName']][$result[$row]['ClientName']] = $result[$row]['PhoneNumber'];
}