Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过php从mysql结果创建json对象_Php_Json - Fatal编程技术网

通过php从mysql结果创建json对象

通过php从mysql结果创建json对象,php,json,Php,Json,可能重复: 我想使用php创建一个json对象,如下所示。它将返回一个字符串作为结果sql查询的响应 {"Orders":[ {"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}, {"DeliveryId":"DeliveryId","CustomerName":"Customer

可能重复:

我想使用php创建一个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(); 
?>

必须为每行创建一个数组,以指定字段名和值

$json['Orders'][] = array('DeliveryId' => $row[0], 'CustomerName' => $row[1], ...);
或者,如果表列名正是您希望在JSON中使用的名称,则使用函数:

$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
    $rows[] = $r;
}
$data = array('Orders' => $rows);
print json_encode($data);

有人知道如何从每个$row结果中获取一行中的所有列吗?不指定每个列名?使用functionNo,使用Thank@dualed。我已经更新了答案有一个关于字符串类型问题的匹配问题+答案:删除你的托管密码