• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

PHP MySQL JSON按数据组织

php 来源:mreynol 4次浏览

我需要能够按类别名称组织我的JSON。我通过Category ID(项目)和Key(类别)将两个表链接在一起。我希望能够将所有带有类别ID标记的项目组织在类别表的类别名称下。这是我到目前为止的代码:PHP MySQL JSON按数据组织

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

任何帮助完成这一点将不胜感激!

===========解决方案如下:

试试这个:

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

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)