gpt4 book ai didi

php - 使用 MySQL 中的键将数组的 JSON 数组创建为单个 JSON 对象

转载 作者:行者123 更新时间:2023-11-29 23:53:50 25 4
gpt4 key购买 nike

我试图在 JSON 对象的循环中创建一个数组数组,但它返回两个对象。如果我用键删除数组周围的数组,它可以工作,但我需要键。

这是我正在寻找的格式:

$shop = array( "1408842145690" => array( id => "1408842145690", 
code => "1",
title => "zdfdsf",
date => "2014-08-01",
description => "fghgf"
),
"1408840099517" => array( id => "1408840099517",
code => "1",
title => "test",
date => "2014-08-01",
description => "this is a test"
)
);echo json_encode($shop);

这是我正在使用的代码

$query = " SELECT * FROM todolist ";
if ($result = mysqli_query($mysqli,$query)) {
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$tasks = array(
$row['task_id'] => array( 'id' => $row['task_id'],
'code' => $row['task_statusbox'],
'title' => $row['task_title'],
'date' => $row['task_date'],
'description' => $row['task_description']
)
);
$alltasks[] = $tasks;
}
echo json_encode($alltasks);
/* free result set */
$result->close();
}

这是我得到的结果:

{"1408842145690":{"id":"1408842145690","code":"1","title":"zdfdsf","date":"2014-08-01 00:00:00","description":"fghgf"}},{"1408840099517":{"id":"1408840099517","code":"1","title":"test","date":"2014-08-01 00:00:00","description":"this is a test"}}

这就是我想要的结果

{"1408842145690":{"id":"1408842145690","code":"1","title":"zdfdsf","date":"2014-08-01","description":"fghgf"},"1408840099517":{"id":"1408840099517","code":"1","title":"test","date":"2014-08-01","description":"this is a test"}}

最佳答案

将 while 循环的内容替换为以下内容:

$tasks = array('id' => $row['task_id'],
'code' => $row['task_statusbox'],
'title' => $row['task_title'],
'date' => $row['task_date'],
'description' => $row['task_description']
);
$alltasks[$row['task_id']] = $tasks;

编辑:我测试了上面的内容,它确实有效。这是完整的代码,替换完好...尝试复制/粘贴。

$query = " SELECT * FROM todolist ";
if ($result = mysqli_query($mysqli,$query)) {
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$tasks = array('id' => $row['task_id'],
'code' => $row['task_statusbox'],
'title' => $row['task_title'],
'date' => $row['task_date'],
'description' => $row['task_description']
);
$alltasks[$row['task_id']] = $tasks;
}
echo json_encode($alltasks);
/* free result set */
$result->close();
}

关于php - 使用 MySQL 中的键将数组的 JSON 数组创建为单个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25468502/

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