laravel控制器中的Foreach,但只有单个数据

时间:2019-02-22 14:27:08

标签: php laravel

我的数据就像

$game = game::all();

0: {gameID: 10802, startTime: "2019-02-19 23:40:51"}
0: {gameID: 10803, startTime: "2019-02-19 23:40:51"}
0: {gameID: 10804, startTime: "2019-02-19 23:40:51"}
0: {gameID: 10805, startTime: "2019-02-19 23:40:51"}

foreach($game as $a){
return response->json($a->gameID); 
}

out put// 10802

我想使用所有gameID,但是我的错误是什么?谢谢

1 个答案:

答案 0 :(得分:3)

您必须将其放入列表中然后返回:

$game = game::all();
$idList = []; //or $idList = array(); if PHP version < 5.2
foreach($game as $a){
    $idList[]=$a->gameID;
}
return response->json($idList);

或者使用pluck上的Collections方法的Laravel方法:

$game = game::all(); 
$plucked = $collection->pluck('gameID'); 
return response->json($plucked->all());