I have an array: $types of:
Array
(
[0] => Array
(
[id] => 1
[cat] => Main
[type] => name0 )
[1] => Array
(
[id] => 2
[cat] => Main
[type] => Name1 )
[2] => Array
(
[id] => 3
[cat] => Main
[type] => Name2 )
[3] => Array
(
[id] => 4
[cat] => Main
[type] => Name3 )
[4] => Array
(
[id] => 5
[cat] => Secondary
[type] => Name4 )
[5] => Array
(
[id] => 6
[cat] => Secondary
[type] => Name5 )
[6] => Array
(
[id] => 7
[cat] => Secondary
[type] => Name6 )
[7] => Array
(
[id] => 8
[cat] => Other
[type] => Name7
)
[8] => Array
(
[id] => 9
[cat] => Other
[type] => Name8
)
[9] => Array
(
[id] => 10
[cat] => Other
[type] => Name9
)
[10] => Array
(
[id] => 11
[cat] => Other
[type] => name10
)
)
And I'd like to re-build it as a multi directional array. But grouped together by cat so they'd be Main, Secondary, and Other *those do or could change from the database. As more get added over time, so using $types['cat']
would be recommended.
Also I have another one. that has cat1/cat2 I'll need to do the same thing with but after i get this one working, i'm hoping i can work that one out.
I've looked on here, and on google. and here has a few similar examples, but I wasn't able to get any of them to work right. As far as I can tell, I think the best route would be to use foreach()
and then build a new array?
Something like this?
<?
$all = array(
array('id'=>1, 'cat'=>'Main','type'=>'Name0'),
array('id'=>2, 'cat'=>'Main','type'=>'Name1'),
array('id'=>3, 'cat'=>'Main','type'=>'Name3'),
array('id'=>4, 'cat'=>'Sec','type'=>'Name4'),
array('id'=>5, 'cat'=>'Sec','type'=>'Name5'),
array('id'=>6, 'cat'=>'Sec','type'=>'Name6'),
);
$result = array();
foreach($all as $array){
$result[$array['cat']][] = array('id'=>$array['id'],'type'=>$array['type']);
}
die(print_r($result));
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.