如何从mysqli prepare(所有匹配的行)获取没有索引的json对象/数组

时间:2018-09-08 08:32:54

标签: php json mysqli prepared-statement

我花了很多时间试图找出从mysql数据库输出json数组/对象的正确方法,像这样:

expected output 
    {
        "ITEM1": 20,
        "ITEM2": 15,
        "ITEM3": 12
    }

每个键/值对对应一个mysql表行(无需显示ID列)。

id |item| price

这是我当前在debian上使用MYSQLND driver的代码:

<?php
header('Content-Type: application/json');

$servername = "localhost";
$username = "root";
$password = "pswd";
$dbname = "json";


$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


$itemInitArr = array();
$decharge = 0;
$stmt = $conn->prepare("SELECT item, price FROM stock WHERE total_sold = ?");
$stmt->bind_param("i", $decharge);
$stmt->execute();
$result = $stmt->get_result();


                            while ($itemInit = $result->fetch_assoc())
                            {
                                $itemInitArr[] = array (
                                            $itemInit['item'] => $itemInit['price']
                                    );
                            }
$stmt->close();                         
$final_data = json_encode($itemInitArr, JSON_PRETTY_PRINT); 
echo $final_data;

$conn->close();
?>

输出以下内容:

[
    {
        "ITEM1": 20
    },
    {
        "ITEM2": 15
    },
    {
        "ITEM3": 12
    }
]

那么,错误在哪里,以及如何解决它以匹配预期的输出?

3 个答案:

答案 0 :(得分:1)

如果将构建数组的方式更改为...

$itemInitArr[$itemInit['item']] =  $itemInit['price'];

答案 1 :(得分:0)

尝试使用

$idx = 1; 
while ($itemInit = $result->fetch_assoc()){
     $itemInitArr['ITEM'.$idx] =  $itemInit['price'];
     $idx++;
}
$final_data = json_encode($itemInitArr, JSON_PRETTY_PRINT); 

如果ITEM1 ... ITEMN是列项目的内容

     $itemInitArr[$itemInit['item']] =  $itemInit['price'];

答案 2 :(得分:0)

  <?php
header('Content-Type: application/json');

$servername = "localhost";
$username = "root";
$password = "pswd";
$dbname = "json";


$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


$itemInitArr = array();
$decharge = 0;
$stmt = $conn->prepare("SELECT item, price FROM stock WHERE total_sold = ?");
$stmt->bind_param("i", $decharge);
$stmt->execute();
$result = $stmt->get_result();


                            while ($itemInit = $result->fetch_assoc())
                            {
                                $itemInitArr[$itemInit['item']] = $itemInit['price'];

                            }
$stmt->close();                         
$final_data = json_encode($itemInitArr, JSON_PRETTY_PRINT); 
echo $final_data;

$conn->close();
?>