我正在尝试在到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();
}

10-04 11:28
查看更多