繁体   English   中英

使用php将mysql数据转换为所需格式的json

[英]To convert mysql data to json in required format using php

我有一个带有值的表

| 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 进行编码。

您必须将您的值作为键附加到每列的数组中:

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;
}

只需添加[]括号,您的数据就不会被覆盖。

    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<count($result); $row++) {
    $values[$result[$row]['SpecificCategoryName']][$result[$row]['ClientName']] = $result[$row]['PhoneNumber'];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM