2016-11-28 15 views
1

私はここで約2時間立ち往生しており、何か助けが必要です。私はPHP JSON 2次元配列出力

を達成しようとしている何

私はmoviesと呼ばれるテーブルを有しており、questionanswercategoryとして行を持つMySQLのDBを持っています。カテゴリは重要です。各カテゴリは、そのカテゴリの値を持つ行を持つ独自の配列として印刷する必要があるためです。

したがって、カテゴリ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

btwありがとう、どうもありがとう! –

+0

それはベースをカバーする必要があります。 – AbraCadaver