Reputation: 409
i need to be able to organize my JSON by category name. I am linking two tables together by Category ID (items) and Key (category). I want to be able to organize all the items tagged with a category ID to be organized under its category name from the category table. Here is my code so far:
$query = "SELECT * FROM items,category WHERE items.category_id = category.key";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
while($row = mysql_fetch_array($result))
extract($row);
$channel['items'][] = array(
'title' => $title,
'category_id' => $category_id,
'category_name' => $category_name,
'category_key' => $key,
);
}
$channels = array($channel);
$json = json_encode($channel);
header('Content-type: application/json');
echo $json;
}
Which outputs JSON like this:
{
"items": [
{
"title": "putting in title",
"category_id": "7",
"category_name": "Stuff 1",
"category_key": "7"
},
{
"title": "another title",
"category_id": "7",
"category_name": "Stuff 1",
"category_key": "7"
},
But i need for the JSON to be organized by Category name, like this:
{
"Stuff 1": [
{
"title": "putting in title",
"category_id": "7",
"category_name": "Stuff 1",
"category_key": "7"
},
{
"title": "another title",
"category_id": "7",
"category_name": "Stuff 1",
"category_key": "7"
},
"Stuff 2": [
{
"title": "putting in title",
"category_id": "7",
"category_name": "Stuff 2",
"category_key": "7"
},
{
"title": "another title",
"category_id": "7",
"category_name": "Stuff 2",
"category_key": "7"
},
Any help to accomplish this would be greatly appreciated!
Upvotes: 0
Views: 195
Reputation: 1289
Try this:
$channel[$category_name][] = array(
'title' => $title,
'category_id' => $category_id,
'category_name' => $category_name,
'category_key' => $key,
);
Upvotes: 1