【问题标题】:json_encode doesn't display all array values [duplicate]json_encode 不显示所有数组值
【发布时间】:2018-02-21 10:04:45
【问题描述】:

我有一个 PHP 脚本,它从表中获取所有记录并将其编码为 JSON。该表共有 246 条记录echo count(); 也返回 246。

问题是,每当我使用json_encode 时,它根本不会显示数组中的值,我看到的只是一个空白页。但是,如果我将记录数减少到 13 条而不是 246 条,它会起作用并显示编码的 JSON 结果。我也尝试将我的 php.ini 文件中的memory_limit 增加到 4095M,但无济于事。

$result = mysqli_query($con, "SELECT * FROM cities");

if (mysqli_num_rows($result) > 0) {
     $response["cities"] = array();
     $city = array();

     while($row = mysqli_fetch_assoc($result)) {
          $city[] = $row;
          array_push($response["cities"], $city);
     }

     $response["success"] = 1;
     echo json_encode($response);
}

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    试试下面,你就会知道到底发生了什么:

    $json = json_encode($response);
    
    if ($json)
        echo $json;
    else
        echo json_last_error_msg();
    

    json_last_error_msg() - 返回最后一次 json_encode() 或 json_decode() 调用的错误字符串

    【讨论】:

    • 谢谢!它返回“格式错误的 UTF-8 字符,可能编码不正确”,让我了解了这个问题:)
    • 很高兴它有帮助!
    【解决方案2】:

    Array "city" 正在为每次调用扩展,并且您在 loop 的每次迭代中推送完整的数组。

    试试:

    while($row = mysqli_fetch_assoc($result)) {
              array_push($response["cities"], $row);
         }
    

    它应该可以工作

    【讨论】:

      【解决方案3】:

      删除$response 数组将$row 推入$cities 数组。推送所有城市后,在json_encode();函数中设置城市并回复echo json_encode(array("cities"=>$cities, "success"=>1));

      if (mysqli_num_rows($result) > 0) {
           $cities = array();
      
           while($row = mysqli_fetch_assoc($result)) {
                array_push($cities, $row);
           }
      
           echo json_encode(array("cities"=>$cities, "success"=>1));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-26
        • 2022-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-01
        • 2021-10-25
        相关资源
        最近更新 更多