I have a table with a list of businesses. Each row has details such as the business name, ID, area,number just to mention a few.
I am querying the mysql database and currently i'm only retrieving the business name and ID.
I am then using the json_encode function to get an output like: {"BusinessA":"business_A_ID","BusinessB":"business_B_ID"}
I would like to be able to retrieve all of the business details and use the json encode function to get an output like:
[
{
"businessName": "BusinessA",
"businessID": "business_A_ID"
},
{
"businessName": "BusinessB",
"businessID": "businees_B_ID"
}
]
Here is the current code i'm using:
$businessRow = array();
$businessResult = mysql_query("SELECT * FROM businessTable");
while($row = mysql_fetch_assoc($businessResult)) {
$businessRow[$row['businessName']] = $row['businessID'];
}
$result = json_encode($businessRow);
echo $result;
So my question is what do I need to change this line to :
$businessRow[$row['businessName']] = $row['businessID'];
in order to get the above JSON output?
Thanks
-
What is the problem what doesn't work?Pekka– Pekka2011年11月05日 11:58:33 +00:00Commented Nov 5, 2011 at 11:58
-
Have you tried json_encode($businessResult);John– John2011年11月05日 12:04:38 +00:00Commented Nov 5, 2011 at 12:04
2 Answers 2
Change your script like this:
$businessRow[] = array(
'businessName' => $row['businessName'],
'businessID' => $row['businessID']
);
Comments
It seems you want:
$rows = array();
$result = mysql_query("SELECT businessName, businessID FROM businessTable");
while($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
echo json_encode($rows);
$row will already be of the form array('businessName' => '...', 'businessID' => '...'), so all you have to do is to add it to your final array and encode it.