2016-11-28 139 views
1

我一直在這裏停留了大約2個小時,我需要一些幫助。PHP JSON 2維陣列輸出

我試圖完成

我有一個MySQL數據庫其中有一個叫movies表,有行如questionanswercategory。類別是重要的。由於每個類別都應該打印爲自己的數組,並且具有該類別值的行。

因此,類別爲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); 

?> 

真誠,吉米!

回答

1

[]動態追加一個新元素到類別數組中。您應該使用mysqli_fetch_assoc()來僅將列名稱作爲索引。另外,如果你希望所有被選中的列,那麼就使用所有的$thearray

while($thearray = mysqli_fetch_assoc($result)) { 
    $category[$thearray['category']][] = $thearray; 
} 

或特定列:

$category[$thearray['category']][] = ['question' => $thearray['question'], 
             'answer' => $thearray['answer']]; 
+0

好吧,你的第二個工作。它現在看起來如何:https://gyazo.com/6612f52889a9e0ff958250bdae67c041 但我怎麼能添加鍵值?我相信像[$ thearray ['Question'=>'question']]],但那不起作用:/ –

+0

感謝順便說一句,你對我的代碼塊的小改動非常有用。非常感謝! –

+0

這應該包括基地。 – AbraCadaver