php - 创建对象数组 PHP
问题描述
我正在尝试在 PHP 上创建这个结构
而且我不知道如何在 PHP 上创建一个对象数组。它总是从对象中获取最后的数据。
这是我当前的代码:
array(
"description": getDescription($id),
"deposit": getPrices($id);
)
function getPrices($id) {
$test = Prices::where('price_id',$id)->where('promo',0)->get();
$price = [];
$data = [];
foreach($test as $t) {
$data["item_id"] = $t->id;
$data["price"] = $t->list;
$data["type"] = $t->type;
$price = $data;
}
return $price;
}
解决方案
getPrices
修复未从函数接收所有记录的实际问题:
array(
"description": getDescription($id),
"deposit": getPrices($id);
)
function getPrices($id) {
$test = Prices::where('price_id',$id)->where('promo',0)->get();
$price = [];
foreach($test as $t) {
$price[] = ["item_id" => $t->id, "price" => $t->list, "type": $t->type];
}
return $price;
}
您在$price
(Correct: $price[]
) 变量之后缺少方括号,该变量告诉 PHP 附加到数组而不是实际替换它。
另一种选择是使用array_push
,它更明确但作用相同;在这里阅读更多。
修复序列化问题:
您可以使用json_encode将数组序列化为 JSON ( Java S cript Object Notation )。
推荐阅读
- android - 如何确定要添加到 android.widget.Space 的 Android gradle 依赖项的库和版本
- python - matplotlib:为什么用 pyplot.setp() 设置网格会导致错误?
- python - 为 Qlistview 的项目添加图标
- php - 还有哪些其他因素可能导致我的 php 脚本超时?
- ios - 屏幕背景颜色
- javascript - 如何使用 clearInterval() 停止不和谐机器人中的循环
- php - 用于 CDN 上的静态远程 HTML 文件的 PHP 包含
- r - 使用 grep 函数在 R 中正确转换数据
- python - 如何打印到文本文件?
- hyperlink - 如何使用 JS 渲染函数在同一列中有多个超链接?