vendredi 19 juin 2020

Combine array based on key in php

I want to combine 2 array in a array where matched item will set under a common array key. Here all items with same category will go under corresponding category.

$categories = category::where('cat_flag','Y')->pluck('id')->toArray();
$items = item::where('item_flag','Y')->get(['item_name','cat_id'])->toArray();

I want to format those into one array like below

$formatedArray = [
                   21=>[{'item_name'=>'abc','cat_id'=>'21'},{'item_name'=>'def','cat_id'=>'21'}],
                   32=>[{'item_name'=>'abc','cat_id'=>'32'}]
                 ]

I have tried with this. I am realizing it's not correct but could not made any solution how to achieve my goal.

$formatedArray = [];

        foreach ($categories as $cat){
            foreach ($items as $itm) {
                $formatedArray[ $cat->id ] = $itm;
            }
        }


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire