I'd like to regroup my array. I have the following:
Array
(
[0] => Array
(
[name] => test1
[item_id] => 1
[category] => cat1
)
[1] => Array
(
[name] => test2
[item_id] => 2
[category] => cat1
)
[2] => Array
(
[name] => test3
[item_id] => 3
[category] =开发者_如何学Go> cat1
)
[3] => Array
(
[name] => test4
[item_id] => 4
[category] => cat2
)
)
I'd like to regroup it like this:
Array
(
[cat1] => Array
(
[0] => Array
(
[name] => test1
[item_id] => 1
)
[1] => Array
(
[name] => test2
[item_id] => 2
)
[2] => Array
(
[name] => test3
[item_id] => 3
)
)
[cat2] => Array
(
[name] => test4
[item_id] => 4
)
)
Can someone tell me how this is best done?
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)
}
}
}
精彩评论