【问题标题】:MySQLI query result (multi-lines) to JSON in PHPMySQLI 查询结果(多行)到 PHP 中的 JSON
【发布时间】:2018-07-03 18:19:31
【问题描述】:

我无法使用 JSON_encode() php 函数查看以 JSON 对象形式返回的 mysql 查询结果的所有行。 这是我的代码:

$Sql_Query = "SELECT * FROM Users";
$result = mysqli_query($dbc,$Sql_Query);
$ligne = array();
$bilan = array();

while ($rowr = mysqli_fetch_assoc($result)) {
    $ligne = array (
        "User_ID" => $rowr['User_ID']
    );
    $bilan[$ligne['User']] = $ligne[[
        ['User_ID'][$rowr['User_ID']]
    ]];
    array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);

它返回我:

{"":null,"0":{"User_ID":"1"},"1":{"User_ID":"19"},"2":{"User_ID":"78"} ,"3":{"User_ID":"79"},"4":{"User_ID":"85"},"5":{"User_ID":"86"},"6":{"User_ID ":"87"},"7":{"User_ID":"88"},"8":{"User_ID":"91"},"9":{"User_ID":"92"}," 10":{"User_ID":"93"},"11":{"User_ID":"94"},"12":{"User_ID":"95"},"13":{"User_ID": "96"},"14":{"User_ID":"97"},"15":{"User_ID":"98"},"16":{"User_ID":"99"},"17" :{"User_ID":"100"},"18":{"User_ID":"101"},"19":{"User_ID":"102"},"20":{"User_ID":"103 "},"21":{"User_ID":"104"},"22":{"User_ID":"105"},"23":{"User_ID":"106"},"24":{ "User_ID":"107"},"25":{"User_ID":"108"},"26":{"User_ID":"109"},"27":{"User_ID":"110"} ,"28":{"User_ID":"111"},"29":{"User_ID":"112"},"30":{"User_ID":"113"},"31":{"User_ID ":"114"},"32":{"User_ID":"115"},"33":{"User_ID":"116"}}

现在,我正在尝试关联 json 输出中每条记录的其他字段。但是当把这个添加到我的代码中时,就没有更多的输出了。

while ($rowr = mysqli_fetch_assoc($result)) {
    $ligne = array (
        "User_ID" => $rowr['User_ID'],
        "User_Nom" => $rowr['User_Nom']
    );      
    $bilan[$ligne['User']] = $ligne[[
        ['User_ID'][$rowr['User_ID']]
    ][
        ['User_Nom'][$rowr['User_Nom']]
    ]];
    array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);

似乎可以显示数值而不是字母字符。

请帮我在同一个输出中混合数字和 alpha 内容。

谢谢 阿诺

【问题讨论】:

  • 您声称正在运行的代码不可能产生您建议的输出。你能用你的实际代码更新一下吗?
  • 我不明白这个代码$bilan[$ligne['User']] = ... 很奇怪,因为$ligne['User'] 没有被设置为一个值,它没有被初始化。

标签: php mysql json associative-array


【解决方案1】:

$ligne['User'] 没有初始化,你可以试试这个:

while ($rowr = mysqli_fetch_assoc($result)) {
    $ligne = array (
        "User_ID" => $rowr['User_ID'],
        "User_Nom" => $rowr['User_Nom']
    );      
    array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);

我用这段代码测试过

$result[] = ['User_ID' => 1, 'User_Nom' => 'Nom1'];
$result[] = ['User_ID' => 2, 'User_Nom' => 'Nom2'];
$result[] = ['User_ID' => 3, 'User_Nom' => 'Nom3'];
$bilan = [];
while ($rowr = array_pop($result)) {
    $ligne = array (
        "User_ID" => $rowr['User_ID'],
        "User_Nom" => $rowr['User_Nom']
    );
    array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);

它提供了这个结果:

{"0":{"User_ID":3,"User_Nom":"Nom3"},"1":{"User_ID":2,"User_Nom":"Nom2"},"2":{" User_ID":1,"User_Nom":"Nom1"}}

注意结果有不同的开始,它不包含

"":null,

还有。这是奇怪的$bilan[undefined] = undefined 行的结果

【讨论】:

    【解决方案2】:

    为了清楚起见,转换为 PHP >= 5.5。

    我在猜测和假设,但我还能做什么?我看到的主要问题是您可能会因数组语法而绊倒。您似乎想通过“User_ID”重新索引结果,我假设这是在每个表记录中找到的一些字符串标识符。

    模块化,程序化的形式...

    /*
        Assuming you are attempting to re-index by the 'User_ID' field
        of each record before encoding as JSON.
    */
    
    function getDb($ip, $user, $password, $database) {
        $db = mysqli_connect($ip, $user, $password, $database);
    
        //error checking etc ...
    
        return $db;
    }
    
    function selectRecords(mysqli $db, $sql) {
        $result = mysqli_query($db, $sql);
    
        if (!$result) {
            throw new UnexpectedValueException("Database query (read) was unsuccessful!");
        }
    
        return $result;
    }
    
    function getUserRecords(mysqli $db) {
        $query = 'SELECT * FROM Users';
        return selectRecords($db, $query);
    }
    
    function reindexByField($newIndex, $userResults) {
        $reindexed = [];
    
        while ($row = mysqli_fetch_assoc($userResults)) {
            if (!isset($row[$newInded])) {
                throw new OutofBoundsException("The index '" . $newIndex . "' does not exist in the tested record");
            }
    
            $redindexed[$row[$newIndex]] = $row;
        }
    
        return $reindexed;
    }
    
    function getJsonFromArray(array $records) {
        $json = json_encode($records, JSON_FORCE_OBJECT);
    
        if (!$json) {
            throw new UnexpectedValueException("Records were not encoded into a JSON formatted string. Got boolean false, instead.");
        }
    
        return $json;
    }
    

    在程序形式中,然后...

    try {
        $db = getDb($ip, $user, $password, $db); // Just pretend for a moment.
        echo getJsonFromArray(reindexByField('User_ID', getUserRecords($db));
    } catch (e) {
        // Your handler code here.
    } finally {
        mysqli_close($db);
    }
    

    面向对象的方法可以使您的代码更有条理。

    【讨论】:

      【解决方案3】:

      你是对的,因为最初的清洁计划,因为它不起作用,我做了太多的修改,最终在不需要的地方增加了复杂性......

      我在 php doc 中发现了了解更多关于在 json 转换中添加其他字段时产生的错误的可能性。 json_last_error() 是理解问题的关键。 所以我补充说:

      switch (json_last_error()) {
              case JSON_ERROR_NONE:
                  echo ' - Aucune erreur';
              break;
              case JSON_ERROR_DEPTH:
                  echo ' - Profondeur maximale atteinte';
              break;
              case JSON_ERROR_STATE_MISMATCH:
                  echo ' - Inadéquation des modes ou underflow';
              break;
              case JSON_ERROR_CTRL_CHAR:
                  echo ' - Erreur lors du contrôle des caractères';
              break;
              case JSON_ERROR_SYNTAX:
                  echo ' - Erreur de syntaxe ; JSON malformé';
              break;
              case JSON_ERROR_UTF8:
                  echo ' - Caractères UTF-8 malformés, probablement une erreur d\'encodage';
              break;
              default:
                  echo ' - Erreur inconnue';
              break;
          }
      

      这返回了一个 UTF-8 编码问题。所以我修改了我的代码添加了一些

      utf8_encode($rowr['Fieldname'])
      

      第一个工作解决方案与@PaulH 的解决方案非常接近,只是,在我的具体情况下,我必须添加 (utf8_encode()) 语句:

          $Sql_Query = "SELECT * FROM Users";
          $result = mysqli_query($dbc,$Sql_Query);
          $ligne =array();
          $bilan = array();
          while ($rowr = mysqli_fetch_assoc($result)) {
              $ligne = array ("User_ID" => $rowr['User_ID'],  
                              "User_Nom" => utf8_encode($rowr['User_Nom']),
                              "User_Prenom" =>utf8_encode($rowr['User_Prenom']));
              array_push ($bilan, $ligne);
          }
          echo json_encode($bilan, JSON_FORCE_OBJECT); 
      

      它现在显示所有字段,所有行。但仍有一些“é”转换为“\u00e9”。所以this post 把最后一块砖解决了。

      我修改了:

      JSON_FORCED_OBJECT

      JSON_UNESCAPED_UNICODE

      作为 json_encode() 参数。

      最后,提供我想要的代码如下:

      $Sql_Query = "SELECT * FROM Users";
      $result = mysqli_query($dbc,$Sql_Query);
      $bilan = array();
      while ($rowr = mysqli_fetch_assoc($result)) {
          $ligne = array ("User_ID" => $rowr['User_ID'],  
                          "User_Nom" => utf8_encode($rowr['User_Nom']),
                          "User_Prenom" =>utf8_encode($rowr['User_Prenom']));
          array_push ($bilan, $ligne);
      }
      echo json_encode($bilan, JSON_UNESCAPED_UNICODE);
      

      【讨论】:

        猜你喜欢
        • 2011-08-21
        • 1970-01-01
        • 2016-11-03
        • 2017-07-24
        • 2013-09-23
        • 1970-01-01
        • 2013-04-23
        • 2012-09-20
        • 2019-03-08
        相关资源
        最近更新 更多