laravel 从循环中获取所有项并显示JSON

uinbv5nw  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(96)

我使用的是LaravelPHP,我在第一个循环中Map了一个id列表来获得一个id产品列表。
因为我返回的是响应,所以它只返回列表中的第一个结果.
我怎样才能将列表中的所有项目返回为json,以便从我的API中输出?

//Loop through and make additional calls to get all storage
            foreach ($ids as $id) {
                // Make additional API calls based on the $id
                $data = Http::get($url.'/'.$id);
                if($data->successful()) {
                   return response()->json(json_decode($data)); 
                }
            }
dhxwm5r4

dhxwm5r41#

您可以:

//Loop through and make additional calls to get all storage
$results = [];

foreach ($ids as $id) {
   // Make additional API calls based on the $id
   $data = Http::get($url.'/'.$id);
   if($data->successful()) {
        $results[] = json_decode($data); 
   }
}

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

相关问题