Home > Software design >  how to flatten and combine array in php
how to flatten and combine array in php

Time:11-09

hi i wrote this code in laravel

return [
    'image' => $this->image,
    $this->categories()->get()->map(function ($category) {
        return [
            $category->name => $category->pivot->image
        ];
    }),
];

that gives me this

"0": [
    {
        "Body": "80229241-2.jpg"
    },
    {
        "Face": "80241166-2.jpg"
    },
    {
        "Painting": "80229241-3.jpg"
    }
],
"image": "81263275-1.jpg"

but i want this for example

    "Body": "80229241-2.jpg",    
    "Face": "80241166-2.jpg",    
    "Painting": "80229241-3.jpg",    
    "image": "81263275-1.jpg"

thank you for your help

CodePudding user response:

Just add flatten() after your map().

$this->categories()->get()->map(function ($category) {
    return [
        $category->name => $category->pivot->image
    ];
})
->flatten()

I think using flatMap() instead of map() also works but I'm not sure.

If you're using PHP 7.4 or newer, you can use short closures.

$this->categories()->get()->map(fn($c) => [$c->name => $c->pivot->image])->flatten()

CodePudding user response:

You can't manipulate array keys with map, but you could use foreach instead:

$array = [];
$array['image'] = $this->image,
$categories = $this->categories()->get();
foreach($categories as $category) {
    $array[$category->name] = $category->pivot->image;
}
return $array;

CodePudding user response:

I belive collection method pluck() is what you are looking for.

$this->categories()->with('pivot')->pluck('name', 'pivot.image')->get();

Should look something likes this assuming pivot is the name of the relation and image is it's attribute.

  • Related