1
我一直在這裏停留了大約2個小時,我需要一些幫助。PHP JSON 2維陣列輸出
我試圖完成
我有一個MySQL數據庫其中有一個叫movies
表,有行如question
,answer
,category
。類別是重要的。由於每個類別都應該打印爲自己的數組,並且具有該類別值的行。
因此,類別爲Two and a Half Men
的所有行都應顯示在下面的Two and a Half Men
數組中。
例子:
[
{
"Arrow": [
"question:","this is a question"
"answer","this is an answer"
],
"How I Met Your Mother": [
"question:","this is a question"
"answer","this is an answer"
],
"South Park": [
"question:","this is a question"
"answer","this is an answer"
],
"The Big Bang Theory": [
"question:","this is a question"
"answer","this is an answer"
],
"The Last Man On Earth": [
"question:","this is a question"
"answer","this is an answer"
]
}
]
我有什麼作爲JSON輸出:
[
{
"Arrow": [
"question without the key value(only the string..)"
],
"How I Met Your Mother": [
"question without the key value(only the string..)"
],
"South Park": [
"question without the key value(only the string..)"
],
"The Big Bang Theory": [
"question without the key value(only the string..)"
],
"The Last Man On Earth": [
"question without the key value(only the string..)"
],
"Two and a Half Men": [
""
]
}
]
我的代碼:
<?php
// Create connection
$con=mysqli_connect("localhost","username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM movies";
if ($result = mysqli_query($con, $sql))
{
$category = array();
while($thearray = mysqli_fetch_array($result))
{
// this is the part where it gets messy. ->
// more columns should show such as question, while the category is only the array.
$category[$thearray['category']] = [$thearray['question']];
array_push($category);
}
header('Content-Type: application/json');
echo json_encode(array($category));
}
// Close connections
mysqli_close($con);
?>
真誠,吉米!
好吧,你的第二個工作。它現在看起來如何:https://gyazo.com/6612f52889a9e0ff958250bdae67c041 但我怎麼能添加鍵值?我相信像[$ thearray ['Question'=>'question']]],但那不起作用:/ –
感謝順便說一句,你對我的代碼塊的小改動非常有用。非常感謝! –
這應該包括基地。 – AbraCadaver