PHP MySQL JSON按数据组织

时间:2013-11-22 17:25:09

标签: php mysql json

我需要能够按类别名称组织我的JSON。我按类别ID(项目)和密钥(类别)将两个表链接在一起。我希望能够组织标记有类别ID的所有项目,以便在类别表中的类别名称下进行组织。到目前为止,这是我的代码:

$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;
}

哪个输出JSON如下:

{
"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"
    },

但我需要按类别名称组织JSON,如下所示:

{
"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"
    },

非常感谢任何有助于实现这一目标的帮助!

1 个答案:

答案 0 :(得分:1)

试试这个:

$channel[$category_name][] = array(
      'title' => $title,
'category_id' => $category_id,
'category_name' => $category_name,
'category_key' => $key,
);