php - 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 行。我究竟做错了什么?
解决方案
您反复为数组成员赋值,需要添加[]
以避免这种情况:
while($row = $result->fetch_object())
{
$arrTotal["Templates"][] = array($row);
}
推荐阅读
- c - 为什么这个程序不能在 C 中工作?
- spring-boot - Spring Boot 云 GCP 无法连接到本地 Google PubSub 模拟器
- angular - Ionic 3 - ngFor 第二次访问中的数据空白
- javascript - Laravel:尝试在视图模板中访问数组内的值
- java - 在 LifecycleObserver 中调用 mainActivity 的方法
- javascript - 如何为本地托管的视频创建 blob url?
- excel - Excel VBA 定时器后删除
- ios - 如何获取tableView的indexPath并在metod prepare上使用indexPath(for segue:)
- javascript - 设置页面加载时音频对象的当前时间
- java - 在春季获取 org.springframework.orm.ObjectOptimisticLockingFailureException