Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Laravel collections keys in only string

I have this Laravel 5.3 tinny collection:

Collection {#325 ▼
  #items: array:8 [▼
    0 => 2638
    1 => 2100
    2 => 5407
    3 => 2970
    4 => 4481
    5 => 1611
    6 => 5345
    7 => 50
  ]
}

And I want combined in only string the values, I need this:

"2638,2100,5407,2970,4481,1611,5345,50"
like image 849
RichardMiracles Avatar asked Dec 16 '16 08:12

RichardMiracles


2 Answers

use implode https://laravel.com/docs/5.3/collections#method-implode

if $collection is the value you have shown then

dd($collection->implode(',')); should give the expected result

And if it's a multi-dimensional array, implode can also accept first arg as the key name:

$collection = collect([
  [ 'title' => 'Hello world' ],
  [ 'title' => 'Another Hello world' ]
]);

$collection->implode('title', ',')
like image 99
Sagar Rabadiya Avatar answered Oct 23 '22 19:10

Sagar Rabadiya


You can use PHP implode() or Laravel ->implode() method on collection:

implode(',', $collection->toArray());

$collection->implode(',');
like image 20
Alexey Mezenin Avatar answered Oct 23 '22 19:10

Alexey Mezenin