简体   繁体   中英

To convert mysql data to json in required format using php

I have a table with values

| CategoryName             | ClientName | Phone Number |
|--------------------------|------------|--------------|
| Mobile repair            | XYZ        | 90000000     |
| Mobile repair            | ABC        | 91111111     |
| Car service              | AZC        | 89999999     |
| TV repair                |  MNB       | 88888888     |
| Car service              | LLL        | 99999999     |

I want JSON in format

{ 
"Mobile Repair" : {"XYZ":"90000000","ABC":"91111111"},
"Car Service" :{ "AZC" : "89999999","LLL":"99999999"},
"TV Repair" :{"MNB","88888888"}
}

But I am getting in the format

{ 
"Mobile Repair" : {"ABC":"91111111"},
"Car Service" :{ "LLL":"99999999"},
"TV Repair" :{"MNB","88888888"}
}

My sql query is

$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."')";

And I am formatting the values as

for($row = 0; $row < count($result); $row++)
{
    $values[$result[$row]['SpecificCategoryName']] = array($result[$row['ClientName']=>$result[$row]['PhoneNumber']);
}

Kindly help in encoding the JSON in the above format.

You have to append your values into the array for each columns as keys :

for($row = 0; $row < count($result); $row++)
{
    $cat = $result[$row]['SpecificCategoryName'];
    $name = $result[$row]['ClientName'] ;
    $phone = $result[$row]['PhoneNumber'] ;

    $values[$cat][$name] = $phone;
}

Or with foreach :

foreach ($results as $row)
{
    $cat = $row['SpecificCategoryName'];
    $name = $row['ClientName'] ;
    $phone = $row['PhoneNumber'] ;

    $values[$cat][$name] = $phone;
}

Just add [] brackets and your data wont overwritten.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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