更改JSON的mysql结果以按键索引
问题描述:
I have a mysql result that I'm fetching as an array and encoding to JSON like so:
$getDisplayPage = "
SELECT p.id as pageID, page_type_id, display_id, slide_order, duration, background_img, pn.ID as panel_id, panel_type_id, cont_id, c.ID as contID, content
FROM pages p
inner join panels pn
on p.id = pn.page_id
inner join content c
on pn.cont_id = c.id
WHERE p.active = 1
and pn.active = 1
AND p.display_id = '".$display."'
";
$showDisplayResult = $mysqlConn->query($getDisplayPage);
while($row=mysqli_fetch_assoc($showDisplayResult))
{
$rows[] = $row;
}
$showDisplays = json_encode($rows);
Which returns a row for each entry, but I need to somehow change it to index by page ID. If you see my JSON below, it returns the correct data but it should actually only have 3 objects/rows as opposed to 5. I need to be able to access all attributes of a given pageID. How can I alter this to give me the correct JSON object?
[{"pageID":"93",
"page_type_id":"2",
"display_id":"2",
"slide_order":null,
"duration":"74",
"background_img":"images\/bg_rainbow.svg",
"panel_id":"86",
"panel_type_id":"2",
"cont_id":"138",
"contID":"138",
"content":"
<\/head>
Left 93<\/p>
<\/body>
<\/html>"},
{"pageID":"93",
"page_type_id":"2",
"display_id":"2",
"slide_order":null,
"duration":"74",
"background_img":"images\/bg_rainbow.svg",
"panel_id":"87",
"panel_type_id":"3",
"cont_id":"139",
"contID":"139",
"content":"
<\/head>
Right 93<\/p>
<\/body>
<\/html>"},
{"pageID":"95",
"page_type_id":"1",
"display_id":"2",
"slide_order":null,
"duration":"123",
"background_img":"images\/bg_rainbow.svg",
"panel_id":"90",
"panel_type_id":"1",
"cont_id":"142",
"contID":"142",
"content":"
<\/head>
Testing a full page for ID 95<\/p>
<\/body>
<\/html>"},
{"pageID":"105",
"page_type_id":"2",
"display_id":"2",
"slide_order":null,
"duration":"54",
"background_img":"images\/bg_rainbow.svg",
"panel_id":"97",
"panel_type_id":"2",
"cont_id":"149",
"contID":"149",
"content":"
<\/head>
This is left content<\/p>
<\/body>
<\/html>"},
{"pageID":"105",
"page_type_id":"2",
"display_id":"2",
"slide_order":null,
"duration":"54",
"background_img":"images\/bg_rainbow.svg",
"panel_id":"98",
"panel_type_id":"3",
"cont_id":"150",
"contID":"150",
"content":"
<\/head>
This is right content<\/p>
<\/body>
<\/html>"}]
答
$getDisplayPage = "
SELECT p.id as pageID, page_type_id, display_id, slide_order, duration, background_img, pn.ID as panel_id, panel_type_id, cont_id, c.ID as contID, content
FROM pages p
inner join panels pn
on p.id = pn.page_id
inner join content c
on pn.cont_id = c.id
WHERE p.active = 1
and pn.active = 1
AND p.display_id = '".$display."'
";
$showDisplayResult = $mysqlConn->query($getDisplayPage);
while($row=mysqli_fetch_assoc($showDisplayResult))
{
$rows[$row['pageID']][] = $row;
}
$showDisplays = json_encode($rows);