为了账号安全,请及时绑定邮箱和手机立即绑定

如何在一个数组中分配另一个数组

如何在一个数组中分配另一个数组

PHP
慕运维8079593 2023-06-30 16:08:18
我有两个数组。我只想将两个数组合并为一个数组。public function get_products() {    $products = DB::table('products')->get();        $arr = array();        foreach ($products  as $item)         {               $productImagedata['image'] = DB::table('product_image')-            >where('product_id', $item->id)->get();            array_combine( $arr, $productImagedata );         }                    $pagedata = collect([ "products" => $products ]);        $data = collect(["status" =>     ["code" => "100", "message" => "Success", "data" =>  $pagedata]]);    return response()->json($data, 200);}在上面的代码中。第二个数组应该包含在第一个数组的值中我只是想喜欢这个 "products": [            {                "product_id": 2,                "product_name": "xyz",                "image": [                    {                        "id": 2,                        "image_name": "i.jpg",                    }                ]            },
查看完整描述

3 回答

?
守着一只汪

TA贡献1872条经验 获得超3个赞

根据您问题中的数据,我猜测$item您的循环中等于


{

    "product_id": 2,

    "product_name": "xyz",

},

在这种情况下,您所需要做的就是添加$productImagedata['image']为数组中的键,同时引用$item.


像这样替换你的循环:


//notice the `&` sign on `$item`. This means we are referencing that variable,

//which basically means that if you change it in the loop, it changes the original as well.

foreach ($products  as &$item) 

{   


    //create image object

    $image_data = DB::table('product_image')->where('product_id', $item->product_id)->get();


    //add image object to `$item` object

    $item->image = $image_data;


查看完整回答
反对 回复 2023-06-30
?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

merge 方法将给定的数组或集合与原始集合合并。如果给定项目中的字符串键与原始集合中的字符串键匹配,则给定项目的值将覆盖原始集合中的值:


$collection = collect(['product_id' => 1, 'price' => 100]);


$merged = $collection->merge(['price' => 200, 'discount' => false]);


$merged->all();


// ['product_id' => 1, 'price' => 200, 'discount' => false]


查看完整回答
反对 回复 2023-06-30
?
MMMHUHU

TA贡献1834条经验 获得超8个赞

那应该有效


public function get_products()

{

    $products = DB::table('products')->get();

    $arr = [];

    foreach ($products as $item) {

        $productImageData['image'] = DB::table('product_image')->where('product_id', $item->id)->get()->toArray();

        $arr = array_combine($arr, $productImageData);

    }

    $pageData = collect(['products' => $products]);

    $data = collect(['status' => [

        'code'    => '100',

        'message' => 'Success',

        'data'    => $pageData]]);

    return response()->json($data);

}


查看完整回答
反对 回复 2023-06-30
  • 3 回答
  • 0 关注
  • 108 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信