首页 > 解决方案 > PHP将数组添加到以字符串为键的数组中

问题描述

我有个问题。我正在使用这段代码:

$sql = "SELECT Id, FileName FROM Templates ORDER BY DateTimeUploaded DESC";

if($result = $conn->query($sql))
{
    if($result->num_rows >= 1) 
    {           
        while($row = $result->fetch_object())
        {
            $arrTotal["Templates"] = array($row);
        }

        $result->free();

    }

    $arrTotal["Source"] = "media/templates/";
    echo json_encode($arrTotal);
}

但是当我打印 json 时,$arrTotal["Templates"]它只有一行,但它有 17 行。我究竟做错了什么?

标签: php

解决方案


您反复为数组成员赋值,需要添加[]以避免这种情况:

while($row = $result->fetch_object())
{
    $arrTotal["Templates"][] = array($row);
}

推荐阅读