【问题标题】:Laravel json convert to array only number PHPLaravel json 仅转换为数组数字 PHP
【发布时间】:2017-03-17 12:49:04
【问题描述】:

我有代码:

return $getId = Permission::select('id')->get();

这段代码返回给我:

[{"id":1},{"id":2},{"id":3},{"id":4}]

我要查询返回的记录格式为:

["1","2","3","4"]

我该怎么做?我尝试使用json_decode,但它不起作用我也尝试使用foreach循环,但结果是一样的。我这样做是因为我想使用array_diff 比较这两个表,但我仍然有错误:

array_diff(): 参数 #1 不是数组

Argument 1 是变量$getId

【问题讨论】:

    标签: php arrays json laravel


    【解决方案1】:

    您想使用pluck()toArray() 方法:

    return $getId = Permission::pluck('id')->toArray();
    

    【讨论】:

    • 你的答案更好:)
    【解决方案2】:

    您可以将结果包装在 Collection 中并使用 pluck 方法:

    $permissions = Permission::select('id')->get();
    $ids = collect($permissions)->pluck('id')->all(); // all() to array
    

    更多关于 Laravel 集合的内容采摘here

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2016-07-07
      • 2013-06-18
      • 1970-01-01
      相关资源
      最近更新 更多