gpt4 book ai didi

php - 如果我需要这些键同时具有值​​(从数据库传递),如何将键添加到 PHP 数组?

转载 作者:行者123 更新时间:2023-11-29 22:15:26 26 4
gpt4 key购买 nike

问题就在这里:我正在尝试编写一个生成动态 PHP 数组的代码。我有一个空数组,需要向其中添加键及其值,这些值是由 MySQL 服务器的 do-while 循环传递的。php代码如下:

$result=mysqli_query($link,"SELECT products_id,voted,rating FROM      table_products $sorting LIMIT 6");
if(mysqli_num_rows($result)>0) {

$a = array();
do {

$row = mysqli_fetch_array($result);
$obj=$row['products_id'];
$rating=$row['rating'];
$voted=$row['voted'];



array_push($a,array('obj'.$obj => array('rating' =>
$rating, 'voted' => $voted)));

} while ($row = mysqli_fetch_array($result)
);}

$json = json_encode($a);
echo $json;

...给我这个 json 字符串:

[{"obj1":{"rating":"25","voted":"5"}},{"obj3":{"rating":"36","voted":"10"}},{"obj5":{"rating":"6","voted":"4"}}]

...但我需要这个:

["obj1":{"rating":"25","voted":"5"},"obj3":{"rating":"36","voted":"10"},"obj5":{"rating":"6","voted":"4"}]

那么我该如何插入这个:

'obj'.$obj => array('rating' => $rating, 'voted' => $voted)

没有将其放入单独的数组中,就像我在代码中所做的那样?我只是不知道实现这个的正确方法。

最佳答案

改变

array_push($a,array('obj'.$obj => array('rating' => $rating, 'voted' => $voted)));

$a['obj'.$obj] = array('rating' =>  $rating, 'voted' => $voted);

关于php - 如果我需要这些键同时具有值​​(从数据库传递),如何将键添加到 PHP 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31242086/

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