Reputation: 1167
I am attempting to make an ordered array based on an unsorted array from an SQL database.
The data that is gotten from the database will look something like this:
Array (
//array ('name', position)
array ('george', 2),
array ('lenny' , 4),
array ('rabbit', 1),
array ('pet' , 3)
)
The idea is to sort the 'names' in an array where position
is there place in the array.
What I would like to to end up being:
Array ( 'rabbit', 'george', 'pet', 'lenny' )
The current way I have attempted this is using split_array()
$result
is the array from the database.
foreach ( $result as $res ){
$a = array(array($res['name'], $res['position']));
array_splice($finalArray, ($res['position'] - 1), 0, $a);
}
The issue is sometimes depending on the order the users are retrieved it will not sort it properly, is there a better way to do this, or is this good and I am doing it wrong? Thanks.
Upvotes: 0
Views: 63
Reputation: 2019
Use uasort
http://php.net/manual/en/function.uasort.php function where you can pass a user defined comparasion function
like this:
$myArray = array(array('bill',3),array('joe',4),array('john',1));
/**
* @desc compare two arrays by the second element
* @param array $a (array to compare with an other)
* @param array $b (array to compare with an other)
* @return int 0|1|-1 equals|first is bigger|second is bigger
*/
function myCompare($a,$b){
if( $a[1] == $b[1] ){
return 0; //if the 2nd elements equals return 0
}
return ( $a[1] > $b[1] )?1:-1; //if the 2nd element of the 1st parameters is bigger returns 1 , else returns -1
}
Usage:
uasort( $myArray, 'myCompare' );
The uasort
manipolates the original array
in place.
Result:
var_dump($myArray);
array(
array('john',1),
array('bill',3),
array('joe',4)
);
Recommendation:
If you could edit the SQL
query , better to short the results in the query with ORDER BY
directive like this:
SELECT `name`,`position`
FROM `mytable` #your table name
WHERE 1 #or your conditions here
ORDER BY `position` ASC #ordering directive
This should run faster. And if use this, recommend to add index
to position
field.
Upvotes: 2