首页 > 解决方案 > 如何在 laravel 中回显这个多维集合

问题描述

第一次来这里,潜伏并搜索了很多,但这次Laravel收藏有问题。试图回显foreach 这个多维集合数组,但我不知道如何。

我已经尝试改变很多方式来展示我所知道的。但无济于事,希望得到一些见解,可能会改变我的方法或其他东西......

从数据库获取的代码

$l = [];
for($i = 0; $i < count($request->products); $i++){
    $l[] = [
          'locaction_id' => $request->products[$i]['location'],
        ];
    $locations[] = DB::table('locations')->select('*')->whereIn('location_id',$l)->get();
};

用于显示数组的代码,尝试了两者$location->stuff$location[0][0]['location_id']出现错误

$location->location_id,输出错误:

无法找到 location_id。

$location[0][0]['location_id']$location['location_id']给出:

StdClass 错误或找不到 location_id。

foreach($locations as $key => $location){
   echo $key. "&nbsp; -" .$location->location_id. "<br>";
};

从数据库返回的数组

array:2 [▼
  0 => Collection {#662 ▼
    #items: array:1 [▼
      0 => {#660 ▼
        +"location_id": 1
        +"loc_name": "A0001"
        +"loc_desc": "Cabinet A North"
        +"created_at": "2019-07-05 10:31:12"
        +"updated_at": null
      }
    ]
  }
  1 => Collection {#688 ▼
    #items: array:1 [▼
      0 => {#686 ▼
        +"location_id": 1
        +"loc_name": "A0001"
        +"loc_desc": "Cabinet A North"
        +"created_at": "2019-07-05 10:31:12"
        +"updated_at": null
      }
    ]
  }
]

希望它能为每个数组产生循环结果。

标签: phparraysmultidimensional-arraylaravel-5.7

解决方案


你可以像这样改变你的方法,

// first fetch all location ids in array
$locationIds = array_column($request->products, "location");
// pass all location ids to fetch data
$locations   = DB::table('locations')->select('*')->whereIn('location_id', $locationIds)->get();
// do foreach loop to fetch that data
foreach($locations as $key => $location){
   echo $key. "&nbsp; -" .$location->location_id. "<br>";
}

如果由于某种原因您正在编写代码段,

for ($i = 0; $i < count($request->products); $i++) {
    $l           = $request->products[$i]['location'];
    // I change it to first instead of get
    $locations[] = DB::table('locations')->select('*')->where('location_id', $l)->first();
}
// do foreach loop to fetch that data
foreach ($locations as $key => $location) {
    echo $key . "&nbsp; -" . $location->location_id . "<br>";
}

推荐阅读