Reputation: 101
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.
Upvotes: 2
Views: 57
Reputation: 484
for($row=0; $row<count($result); $row++) {
$values[$result[$row]['SpecificCategoryName']][$result[$row]['ClientName']] = $result[$row]['PhoneNumber'];
}
Upvotes: 0
Reputation: 2197
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);
Upvotes: 0
Reputation: 19764
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;
}
Upvotes: 2