0

I'd like to regroup my array. I have the following:

[ ['name' => 'test1', 'item_id' => 1, 'category' => 'cat1'], ['name' => 'test2', 'item_id' => 2, 'category' => 'cat1'], ['name' => 'test3', 'item_id' => 3, 'category' => 'cat1'], ['name' => 'test4', 'item_id' => 4, 'category' => 'cat2'], ] 

I'd like to regroup it like this:

[ 'cat1' => [ ['name' => 'test1', 'item_id' => 1], ['name' => 'test2', 'item_id' => 2], ['name' => 'test3', 'item_id' => 3], ], 'cat2' => [ ['name' => 'test4', 'item_id' => 4], ], ] 

Can someone tell me how this is best done?

2
  • 3
    That's not "reorder", that's "regroup". Commented Dec 24, 2010 at 9:44
  • Thanks. I'll change my title and amend my post. Commented Dec 24, 2010 at 9:46

1 Answer 1

4

Just loop through it and regroup it... for example:

$array = array( array( 'name' => 'test1', 'itemd_id' => 1, 'category' => 'cat1', ), array( 'name' => 'test2', 'itemd_id' => 2, 'category' => 'cat1', ), array( 'name' => 'test3', 'itemd_id' => 3, 'category' => 'cat1', ), array( 'name' => 'test4', 'itemd_id' => 4, 'category' => 'cat2', ), ); $newArray = array(); foreach($array as $arrayKey => $arrayElement){ $tmpCat = $arrayElement['category']; unset($arrayElement['category']); $newArray[$tmpCat][] = $arrayElement; } var_dump($newArray); array(2) { ["cat1"]=> array(3) { [0]=> array(2) { ["name"]=> string(5) "test1" ["itemd_id"]=> int(1) } [1]=> array(2) { ["name"]=> string(5) "test2" ["itemd_id"]=> int(2) } [2]=> array(2) { ["name"]=> string(5) "test3" ["itemd_id"]=> int(3) } } ["cat2"]=> array(1) { [0]=> array(2) { ["name"]=> string(5) "test4" ["itemd_id"]=> int(4) } } } 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Hannes, I knew there was a cleaner method. This works nicely. Could you explain your code so that I can understand it please?
when you say cleaner, you mean build in? as far i know, no, but there are a ton of array functions in php so I'm not a 100% on that, well in that case iterate through the existing array, and create a new one using the category value of each array element as main key for the new one, and then assign the element as a new value to that
Exactly. What I was going to do was completely rebuild the array moving the key value pairs around. What you did in 3 lines would have taken me 15 lines. Your method is cleaner. I think I see that this line: $newArray[$tmpCat][] = $arrayElement is what does it.
exactly, the ` $tmpCat = $arrayElement['category']; unset($arrayElement['category']);` is not really mendatory, you could use the value directly, but then you would end up with having the cat2 as a value and a key - glad i could help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.