jdubwelch Posted November 28, 2006 Share Posted November 28, 2006 i have three arrays:[code]Array "ONE"( [0] => Vince [1] => Papale [2] => 1 [3] => 46 [4] => 46 [5] => 0 [6] => 46)Array "TWO"( [0] => Brian [1] => Pollard [2] => 10 [3] => 293 [4] => 29.3 [5] => 4 [6] => 77)Array "THREE"( [0] => Johnny [1] => King [2] => 3 [3] => 34 [4] => 10.3 [5] => 2 [6] => 16)[/code]the arrays are named, ONE, TWO, and THREE.i want to be able to sort them according to different keys.for example: i want the arrays to be be in order of their 2nd key.so the order would be:TWO THREE ONEHow would i do that? Link to comment https://forums.phpfreaks.com/topic/28761-sorting-multiple-arrays-by-the-same-key/ Share on other sites More sharing options...
Psycho Posted November 28, 2006 Share Posted November 28, 2006 There are two different approaches. First of all I would put the arrays into one multidimensional array like this:[code]<?php$multiarray["one"] = array( 0 => Vince, 1 => Papale, 2 => 1, 3 => 46, 4 => 46, 5 => 0, 6 => 46);$multiarray["two"] = array( 0 => Brian, 1 => Pollard, 2 => 10, 3 => 293, 4 => 29.3, 5 => 4, 6 => 77);$multiarray["three"] = array( 0 => Johnny, 1 => King, 2 => 3, 3 => 34, 4 => 10.3, 5 => 2, 6 => 16);?>[/code]Then, you could use this (but you will lose the key associations - i.e. the first array will be index [0] not index ["two"]):[code]<?phpfunction sortArray($a, $b) { if($a[2] == $b[2]) { return 0; } return ($a[2] < $b[2]);}usort($multiarray, "sortArray");?>[/code]EDIT: I forgot to mention the other approach which would be to use the function array_multisort(). But, after realizing you would have to convert your arrays in such a way that the data would be in a fundamentally different format I decided against creating an example. Link to comment https://forums.phpfreaks.com/topic/28761-sorting-multiple-arrays-by-the-same-key/#findComment-131657 Share on other sites More sharing options...
The Little Guy Posted November 28, 2006 Share Posted November 28, 2006 You could get the value of 2 from the array, and save it in a new array, then order that new array as the order of the original arrays (if that makes any sense). Link to comment https://forums.phpfreaks.com/topic/28761-sorting-multiple-arrays-by-the-same-key/#findComment-131659 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.