首页 > 解决方案 > 创建对象数组 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;
}

标签: php

解决方案


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


推荐阅读