想在laravel上返回Value json

时间:2018-09-18 10:27:27

标签: php mysql json laravel

我想问一下如何返回json,结果只有VALUE。

我的控制器中有这样的代码:

$firstName = User::select('user_first_name')->get();

$firstNameArray = array();

foreach ($firstName as $firstNames) {
    $firstNameArray[] = $firstNames->$firstName;
}


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

当前结果是:

[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]

当我检查数据库时,有我的数据。当我这样编码时

$firstName = User::select('user_first_name')->get();

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

这将显示以下结果:

[
    {"user_first_name":"Jillian"},
    {"user_first_name":"Kayden"},
    {"user_first_name":"Alize"},
    {"user_first_name":"Kelli"},
    {"user_first_name":"Loyce"},
    {"user_first_name":"Jarrell"},
    {"user_first_name":"Vivianne"},
    {"user_first_name":"Annalise"},
    {"user_first_name":"Rosalee"},
    {"user_first_name":"Jerrod"},
    {"user_first_name":"Yvette"},
    {"user_first_name":"Libby"},
    {"user_first_name":"Lorenz"},
    {"user_first_name":"Alisha"},
    {"user_first_name":"Jerrold"},
    {"user_first_name":"Amya"},
    {"user_first_name":"Columbus"},
    {"user_first_name":"Gwen"},
    {"user_first_name":"Kaylie"},
    {"user_first_name":"Lafayette"}
]

我的问题是,如何在不显示NULL的情况下将名称显示为ARRAY。

3 个答案:

答案 0 :(得分:2)

foreach循环中的语句中删除$符号,并使用user_first_name代替firstName

foreach ($firstName as $firstNames) {
    $firstNameArray[] = $firstNames->user_first_name;
}

答案 1 :(得分:1)

您可以使用pluck方法:

Queue

答案 2 :(得分:0)

尝试一下

$firstname = User::select('user_first_name')->get();

return $firstname;

输出将是:

[
    { "user_first_name": "test name" },
    { "user_first_name": "test name" }
]