2016-05-09 9 views
0

私はJSONデータを生成するコードのが、このを使用していますが、MySQLのテーブルを形成:PHPのMySQLのJSON文書メイク

$sql = "select * from u3D15"; 
$result = mysql_query($sql); 
$json = array(); 
if(mysql_num_rows($result)){ 
    while($row=mysql_fetch_row($result)){ 
     $json['title'][]=$row; 
    } 
} 
mysql_close($db_name); 
echo json_encode($json); 

しかし、これは次のようにJSONが見えるものです:私はそれが好き{"title":[["1","kevin","t0E0GAA"]]}

be:

{ 
    "title" : "Decode JSON", 
    "ID" : 20, 
    "buttons" : 
    [ 
    { 
     "title" : "kevin ", 
     "image" : "t0E0GAA" 
    }, 
    { 
     "title" : "lora ", 
     "image" : "v1AWYqR" 
    } 
    ] 
} 

ファイルの構成を変更するにはどうすればよいですか?

答えて

1

自分で配列を設定してフォーマット結果を取得します。

$json = array(); //create empty array 
$json["title"] = "Decode JSON"; 
$json["ID"] = 20; 
$json["buttons"] = array(); //empty nested array - we will fill it by MySQL results 

$sql = "select * from u3D15"; 
$result = mysql_query($sql); 
if(mysql_num_rows($result)){ 
    while($row=mysql_fetch_row($result)){ 
     $json["buttons"][]=$row; //insert mysql rows to buttons array 
    } 
} 
mysql_close($db_name); 
echo json_encode($json); 
+0

このプリント ' {"title": "JSONをデコードする"、 "ID":20、 "buttons":["kevin"、 "t0E0GAA"]、["tim"、 "uGmSNxk"]]} ' "kevin"、 "image": "t0E0GAA"、 –

+0

mysql_fetch_rowをmysql_fetch_assocに変更しました –

1

それは非常に簡単です、ちょうどこのようなあなたの配列を作成:

$json['title']='Decode JSON'; 
$json['ID']='20'; 
$json['buttons']['title']='kevin'; 
$json['buttons']['image']='t0E0GAA'; 

echo "<pre>"; 
echo json_encode($json); 
1

をコードの下に試してみてください。これはあなたの目的を解決

$sql = "select * from u3D15"; 
$result = mysql_query($sql); 
$json = array(); 
if(mysql_num_rows($result)){ 
    while($row=mysql_fetch_row($result)){ 
     $json['title']=$row[1]; 
     $json['ID']=$row[0]; 
     $json['buttons']['title']=$row[1]; 
     $json['buttons']['image']=$row[2]; 
    } 
} 
mysql_close($db_name); 
echo json_encode($json); 

・ホープ..

+0

これは動作しますが、2行のうちの1つだけを出力します。これをどのように修正できますか? –

+0

あなたはmysql_fetch_assocの代わりにmysql_fetch_rowを使用しているので..私はあなたがただ一つの行を必要と思った:) – Sid