4

I have a list below and i want to get a list of value as comma-separated values:

[{"id":49},{"id":61},{"id":5},{"id":58}] 

I tried pluck but it only returns single value. I want:

49,61,5,58

I can do it in many ways but i want to do it in laravel way.

Code:

   $locations = Location::select('id')->whereIn('id', function($query) use ($id)
            {
                $query->select('location_id')
                    ->from('users_locations')
                    ->whereRaw('user_id ='.$id);
            })->get();
Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49

5 Answers5

15

Using the collection class you can do this, since it's json you have to decode it first so it's an array, which you can convert to a Illuminate\Support\Collection.

$data = json_decode('[{"id":49},{"id":61},{"id":5},{"id":58}]', true);
$csv_data = collect($data)->pluck('id')->implode(',');

If you want the array of values instead of the string, remove the implode call.


After seeing your code this should work just fine.

$csv_data = $locations->pluck('id')->implode(',');
Björn
  • 5,696
  • 1
  • 24
  • 34
Alex
  • 1,425
  • 11
  • 25
2

Try like this

$t='[{"id":49},{"id":61},{"id":5},{"id":58}]' ;
$ARRAY=json_decode($t,true);
$ARRAY=array_column($ARRAY,'id')
$VALUE=implode(',',$ARRAY);

IT GIVE OUTPUT AS

enter image description here

With simple json_decode() ,array_column() and implode()

Bibhudatta Sahoo
  • 4,808
  • 2
  • 27
  • 51
1

Since it's a standard collection, you don't need to use json_decode(). Collection pluck() method will work:

$collection->pluck('id');

You can also use Eloquent's pluck() method instead of using select() and get().

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

1st: use json_decode decode the json string into array

2nd : use array_column to get the specific column from array

3rd : use implode to break the array into string .

<?php

$array ='[{"id":49},{"id":61},{"id":5},{"id":58}]';

echo implode(',',array_column(json_decode($array,true),'id'));

?>

I can do it in many ways but i want to do it in laravel way. That's why i deleted my answer while !!!

JYoThI
  • 11,977
  • 1
  • 11
  • 26
0

You can try this

$data_arr = json_decode('[{"id":49},{"id":61},{"id":5},{"id":58}]', true);
$resultarr = array();
foreach($data_arr as $data){
    $resultarr[] = $data['id'];
}
echo implode(',', $resultarr);
Dev
  • 612
  • 2
  • 13
  • 33