如何将多个数组转换为单独的键和值

时间:2019-06-13 15:47:06

标签: arrays laravel

我想将箔纸数组转换为键的单独数组和值的单独数组$ products_selected_leeds返回跟随的数组,而我只需要数组中的键

$products_selected_leeds = DB::table('Products_selected_leeds')->select('product_id')->whereIn('leed_id',$where_in)->get();

dd($products_selected_leeds);

array:42 [
  0 => {#903
    +"product_id": 152
  }
  1 => {#904
    +"product_id": 756
  }
  2 => {#905
    +"product_id": 938
  }
  3 => {#906
    +"product_id": 172
  }
  4 => {#907
    +"product_id": 1200
  }
  5 => {#908
    +"product_id": 751
  }
  6 => {#909
    +"product_id": 753
  }
  7 => {#910
    +"product_id": 754
  }
  8 => {#911
    +"product_id": 755
  }

预期结果

product_id =  [152 756,938,172,1200,751,753,754,755]

3 个答案:

答案 0 :(得分:0)

也许这会起作用

$products_selected_leeds = DB::table('Products_selected_leeds')->select('product_id')->whereIn('leed_id',$where_in)->pluck('product_id')->toArray();

答案 1 :(得分:0)

您必须使用->pluck()方法

$products_selected_leeds->pluck('product_id')->toArray();

或者您可以使用

DB::table('Products_selected_leeds')->whereIn('leed_id',$where_in)->pluck('product_id')->toArray();

答案 2 :(得分:0)

正如您所说的那样,将所有ID放入单个数组

$query = DB::table('Products_selected_leeds')
                ->select('product_id')
                ->whereIn('leed_id',$where_in)
                ->get()
                ->pluck('product_id')
                ->toArray();

还有dd($query)

针对拉弗尔·弗森(BELOW 5.3)进行了编辑,但没有将查询实例上的收集实例退回

https://github.com/laravel/framework/pull/10552

    $query = DB::table('Products_selected_leeds')
            ->select('product_id')
            ->whereIn('leed_id',$where_in)
            ->get();               

    $toCollection = collect($query);

    $arrayOfIds = $toCollection->pluck('product_id')->toArray();

    dd($arrayOfIds);

请在下面发表评论,如果有任何问题或将我的答案标记为“如果工作正常则表示接受”