PHP MySQL JSON按数据组织

我需要能够按类别名称组织我的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,

);

以上是 PHP MySQL JSON按数据组织 的全部内容, 来源链接: utcz.com/qa/260047.html

回到顶部