2012-12-19 70 views
-3

可能重複:
How to generate .json file with PHP?如何通過PHP創建的Json

我想用PHP創建一個JSON像下面。它將返回一個字符串json作爲結果sql查詢的響應。我該怎麼做?

{"Orders":[ 
      {"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}, 
      {"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}    
] 
} 

我的代碼

<?php 
mysql_connect("mysql12.000webhost.com","a4602996_longvan","longvan2012"); 
mysql_select_db("a4602996_lv"); 
$id=$_POST[user]; 
$sql=mysql_query("select * from testlongvan where Status = 'PACKED'"); 

$json = array(); 
if(mysql_num_rows($sql)){ 
while($row=mysql_fetch_row($sql)){ 
$json['Orders'][]=$row; 
} 
} 

//while($row=mysql_fetch_assoc($sql)) 
//$output[]=$row; 
print(json_encode($json)); 
mysql_close(); 
?> 

但是,當使用我的代碼我收到的結果,不會導致我想:

{ 「訂單」: [ 「longvan」 「10/12/2012」,「Be34433jh」,「Long Van」,「115 Pham Viet Chanh,quan Binh Thanh」,「http://longvansolution.tk/image/sample.jpg」,「PACKED」,「0909056788 「], [」takeshi「,」24/12/2012「,」BF6464633「,」Vn-zoom「,」16 nguyen cuu van,quan binh thanh「,」http:// longvansolution.tk/image/hoadon3.jpg","PACKED","098897657" ] ]} 你能幫幫我!

+0

你能告訴我們你的SQL查詢? – jamis0n

+0

爲什麼downvote?原因? – Elbek

+0

['json_encode()'](http://php.net/manual/en/function.json-encode.php) –

回答

0
// SERVER SIDE 
<?php 
    //... create array 
    //....Obviously you would use your own SQL link and query 
    $animals = array(); 
    $result = @mysqli_query('YOUR DB LINK', 'YOUR QUERY'); 

    while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) { 
     array_push($animals, array(
      'animal' => $row['animal'], 
      'sound' => $row['sound'] 
    )); 
    } 
?> 

// CLIENT SIDE 
<html> 
<script> 
    // RETURN FROM PHP PAGE ECHO VIA AJAX PERHAPS // 
    var animals = <?php echo json_encode($animals) ?>; 

    $.each(animals, function (i, elem) { 
     console.log(elem.animal + " makes a " + elem.sound); 
    }); 
</script> 
</html> 
0

您可以使用json_encode()功能來做到這一點。

而你的JSON格式無效。使用:代替=

+0

請對你的downvote發表評論? – Stanley