Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert array two dimensional to collection laravel?

I have array like this :

$test = array(
    array(
        'name' => 'Christina',  
        'age' => '25' 
    ),
    array(
        'name' => 'Agis', 
        'age' => '22'
    ),
    array(
        'name' => 'Agnes', 
        'age' => '30'
    )
);

I want to change it to collection laravel

I try like this :

collect($test)

The results are not perfect. There is still an array

How can I solve this problem?

like image 270
moses toh Avatar asked Jul 23 '18 23:07

moses toh


3 Answers

collect($test) does not convert $test to a collection, it returns $test as a collection. You need to use it's return value for a new variable, or override the existing one.

$test = collect($test);

If you want to convert the individual items to objects (instead of arrays) like you indicated in the comment below, then you will need to cast them.

$test = collect($test)->map(function ($item) {
    return (object) $item;
});
like image 181
Dwight Avatar answered Oct 21 '22 14:10

Dwight


I know it's been a while, but i found this answer on laracast and it seems to solve the issue better, cause it make it recursive. This solution I've got from https://gist.github.com/brunogaspar/154fb2f99a7f83003ef35fd4b5655935 github and works like a charm.

\Illuminate\Support\Collection::macro('recursive', function () {
return $this->map(function ($value) {
    if (is_array($value) || is_object($value)) {
        return collect($value)->recursive();
    }

    return $value;
});

});

than you go like:

$data = [
[
    'name' => 'John Doe',
    'emails' => [
        '[email protected]',
        '[email protected]',
    ],
    'contacts' => [
        [
            'name' => 'Richard Tea',
            'emails' => [
                '[email protected]',
            ],
        ],
        [
            'name' => 'Fergus Douchebag', // Ya, this was randomly generated for me :)
            'emails' => [
                '[email protected]',
            ],
        ],
    ],
  ],
];
$collection = collect($data)->recursive();
like image 37
Rodrigo Klim Avatar answered Oct 21 '22 13:10

Rodrigo Klim


To share more light.

Collections are "macroable", which allows you to add additional methods to the Collection class at run time. According to Laravel explanation on collections. Arrays can be dimensional. using the map function extends your collection to convert child array into objects

$test = array(
    array(
        'name' => 'Christina',  
        'age' => '25' 
    ),
    array(
        'name' => 'Agis', 
        'age' => '22'
    ),
    array(
        'name' => 'Agnes', 
        'age' => '30'
    )
);

// can be converted using collection + map function
$test = collect($test)->map(function($inner_child){
    return (Object) $inner_child;
});

This will cast the inner child array into Object.


like image 2
Codedreamer Avatar answered Oct 21 '22 14:10

Codedreamer