gpt4 book ai didi

php - 从数据库中的产品生成 JSON,只取最后一行

转载 作者:行者123 更新时间:2023-11-29 06:32:42 25 4
gpt4 key购买 nike

列在名为“products”的表中是这样设置的

+------------++---------------++----------------------++---------------++----------------+
| product_id | product_name | product_description | product_image | product_price |
+------------++---------------++----------------------++---------------++----------------+
| 1 | a1 | good | url.jpg | 150dkk |
+------------++---------------++----------------------++---------------++----------------+
| 2 | a2 | nice | url.jpg | 150dkk |
+------------++---------------++----------------------++---------------++----------------+

这是我的代码,所以我循环遍历我的产品表并将它们推送到一个将是 JSON 的数组中。

    //Create an array
$json_response = json_decode('{"products":[]}');

$sql = "SELECT * FROM products";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)){
$row_array['id'] = $row['product_id'];
$row_array['name'] = $row['product_name'];
$row_array['description'] = $row['product_description'];
$row_array['image'] = $row['product_image'];
$row_array['price'] = $row['product_price'];
}
// Push the columns into the created array
array_push($json_response->products, $row_array);

// Encode into an object
$oJsonResponse = json_encode($json_response);

// Save it in a new file that holds the json from MySQL
file_put_contents('products.json', $oJsonResponse);

问题是我只能设法将 ID 为 2 的产品放入我的 json 文件中,因此第一个产品永远不会保存在 .json 文件中。当我执行 echo = "$row[product_name]"; - 我得到两种产品

最佳答案

开始吧(将 array_push 移入 while 循环)

<?php

//Create an array
$json_response = array();

$sql = "SELECT * FROM products";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result)) {
$row_array['id'] = $row['product_id'];
$row_array['name'] = $row['product_name'];
$row_array['description'] = $row['product_description'];
$row_array['image'] = $row['product_image'];
$row_array['price'] = $row['product_price'];

// Push the columns into the created array
$json_response[] = $row_array;
}

// Encode into an object
$oJsonResponse = json_encode($json_response);

// Save it in a new file that holds the json from MySQL
file_put_contents('products.json', $oJsonResponse);

关于php - 从数据库中的产品生成 JSON,只取最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26936185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com