gpt4 book ai didi

php - 在服务器上生成一个 JSON 对象并在客户端迭代它

转载 作者:行者123 更新时间:2023-11-30 18:32:17 25 4
gpt4 key购买 nike

我的 php 方面

   $i = 1;
while ($row = mysql_fetch_array($query)) {
$productarray[$i][] = $row['product_id'];
$productarray[$i][] = $row['product_model'];
$productarray[$i][] = $row['product_type'];
$productarray[$i][] = $row['product_return'];
$i++;
}
$jsonstring = json_encode($productarray);

这就是我得到的 这是一个有效的 json 字符串吗

{
"1":["1","HFJ5G1.5","plat","graviteits"],
"2":["2","HHJ5S2.5","holle plunjer","veer"],
"3":["3","HTJ5S7.5","inbouw","veer"]
}

我不能遍历这个有人请告诉我如何迭代这个 json

从 json 站点我认为这是格式,如果是的话我如何将上面的 json 字符串更改为这种格式?

{
"1":[{"1","HFJ5G1.5","plat","graviteits"}],
"2":[{"2","HHJ5S2.5","holle plunjer","veer"}],
"3":[{"3","HTJ5S7.5","inbouw","veer"}]
}

最佳答案

您需要稍微重构您的 PHP 代码。尝试做这样的事情:

$productarray = array();
while ($product = mysql_fetch_assoc($query)) { // NOTE: using associative array
$productarray[] = $product;
}
echo json_encode($productarray);

// Output
// [{
// "product_id": "1",
// "product_model": "HFJ5G1.5",
// "product_type": "plat",
// "product_rturn": "graviteits"
// }, {
// "product_id": "2",
// "product_model": "HHJ5S2.5",
// "product_type": "holle plunjer",
// "product_rturn": "veer"
// }, {
// "product_id": "3",
// "product_model": "HTJ5S7.5",
// "product_type": "inbouw",
// "product_rturn": "veer"
// }]

请注意,它现在变得非常容易迭代。您可以按如下方式进行:

var o = [{
"product_id": "1",
"product_model": "HFJ5G1.5",
"product_type": "plat",
"product_rturn": "graviteits"
}, {
"product_id": "2",
"product_model": "HHJ5S2.5",
"product_type": "holle plunjer",
"product_rturn": "veer"
}, {
"product_id": "3",
"product_model": "HTJ5S7.5",
"product_type": "inbouw",
"product_rturn": "veer"
}];
for (var i = 0; i < o.length; i++) {
console.log("Product " + (i + 1) + " has model:" + o[i]["product_model"]);
console.log("Product " + (i + 1) + " has type:" + o[i]["product_type"]);
}

关于php - 在服务器上生成一个 JSON 对象并在客户端迭代它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9307839/

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