ifm1989 Posted October 26, 2007 Share Posted October 26, 2007 I've been having trouble here. This is my array: Array ( [group_1] => Array ( [0] => Array ( [id] => 1 [name] => test2 [group] => group_1 [unlock] => 5 ) [1] => Array ( [id] => 2 [name] => test1 [group] => group_1 [unlock] => 4 ) [2] => Array ( [id] => 3 [name] => test3 [group] => group_1 [unlock] => 2 ) ) ) I'm try to re-arrange this array it displays everything in order of `unlock`. Think of `unlock` as the points needed to unlock this array item, and I want to sort all items from least requirements to max requirements. This is my horrible attempt: foreach($technologies as $cat => $array){ $technologies[$cat] = sort($technologies[$cat]['unlock']); } Let me know if you need more help understanding, or if you have a solution. Quote Link to comment https://forums.phpfreaks.com/topic/74848-arrange-array-via-php/ Share on other sites More sharing options...
GingerRobot Posted October 26, 2007 Share Posted October 26, 2007 You'll need to specify your own sorting function and use the usort() function. Quote Link to comment https://forums.phpfreaks.com/topic/74848-arrange-array-via-php/#findComment-378452 Share on other sites More sharing options...
Barand Posted October 26, 2007 Share Posted October 26, 2007 this assumes one or more groups in the array <?php $technologies = Array ( 'group_1' => Array ( '0' => Array ( 'id' => 1, 'name' => 'test2', 'group' => 'group_1', 'unlock' => 5 ), '1' => Array ( 'id' => 2, 'name' => 'test1', 'group' => 'group_1', 'unlock' => 4 ), '2' => Array ( 'id' => 3, 'name' => 'test3', 'group' => 'group_1', 'unlock' => 2 ) ), 'group_2' => Array ( '0' => Array ( 'id' => 4, 'name' => 'test4', 'group' => 'group_2', 'unlock' => 4 ), '1' => Array ( 'id' => 5, 'name' => 'test5', 'group' => 'group_2', 'unlock' => 1 ), '2' => Array ( 'id' => 6, 'name' => 'test6', 'group' => 'group_2', 'unlock' => 2 ) ) ); function mysort ($a,$b) { if ($a['unlock'] == $b['unlock']) return 0; return ($a['unlock'] < $b['unlock']) ? -1 : 1; } foreach ($technologies as $cat => $data) { usort($data, 'mysort'); $technologies[$cat] = $data; // replace with sorted array } echo '<pre>', print_r($technologies, true), '</pre>'; ?> Quote Link to comment https://forums.phpfreaks.com/topic/74848-arrange-array-via-php/#findComment-378488 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.