简体   繁体   English

打印出json数组

[英]printing out a json array

I am trying to figure out how to print a json array. 我试图弄清楚如何打印一个json数组。 I am trying to handle this from Android code but it is not working. 我试图从Android代码处理这个,但它无法正常工作。 I believe the problem lies in how I am outputting json. 我相信问题在于我如何输出json。 the below doesn't show anything. 以下没有显示任何内容。 The script is below: 脚本如下:

<?php
// Create connection
$conn=mysqli_connect("localhost","dhdkahd","dsdajdsa","dsadjsajd");
$json = array();
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if (!$conn->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $conn->error);
}


$sql='SELECT title, description, country, city, rate FROM discounts';

$rs=$conn->query($sql);

if($rs === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {

    /*$rs->data_seek(0);
    while($row = $rs->fetch_assoc()){
        echo $row['title'] . '<br>';
    }*/

    while ( $row = $rs->fetch_assoc() )
    {
        $json[] = json_encode($row,JSON_UNESCAPED_UNICODE);
    }
}
//echo json_decode($json);
echo json_encode($json);

mysqli_close($conn);
?>

thanks in advance 提前致谢

You can only call json_encode once . 你只能调用一次 json_encode You're double-encoding everything. 你是对所有内容进行双重编码的。

The line where you're adding data to the array needs to be 您要向阵列添加数据的行必须是

    $json[] = $row;

Then, when the array is built up, you encode the entire thing in one single call: 然后,在构建阵列时,您可以在一次调用中对整个事物进行编码:

echo json_encode($json);

You call json_encode twice. 你两次调用json_encode。 To fix it, change your code to: 要解决此问题,请将代码更改为:

if($rs === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {

    /*$rs->data_seek(0);
    while($row = $rs->fetch_assoc()){
        echo $row['title'] . '<br>';
    }*/

    while ( $row = $rs->fetch_assoc() )
    {
        $json[] = $row;
    }
}
//echo json_decode($json);
echo json_encode($json);

mysqli_close($conn);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM