简体   繁体   中英

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;
    }
}

Try this one:

$formatedArray = [];

foreach ($categories as $category) {
    foreach ($items as $item) {
        if ($item['cat_id'] == $category) {
            $formatedArray[$category][] = $item;
        }
    }
}

Note: if the cat_id (example: 'cat_id'=>'32') needs to be a string, then you need to cast the value.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM