0

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!

1 Answer 1

1

Try this:

$channel[$category_name][] = array(
      'title' => $title,
'category_id' => $category_id,
'category_name' => $category_name,
'category_key' => $key,
);
Sign up to request clarification or add additional context in comments.

2 Comments

OMG! That was too easy! I'm embarassed. Thank you Lauri. What if i need to put everything into a items array too? How would i go about that please?
You mean $channel['items'][$category_name]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.