0

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.

4
  • 3
    why not sort in the database as part of the query? SELECT name, ord FROM table ORDER BY ord Commented Apr 23, 2013 at 8:02
  • @AleksG I feel bad now :( lol so simple, thanks! Commented Apr 23, 2013 at 8:10
  • Just smile and use it. Commented Apr 23, 2013 at 8:16
  • @AleksG Oh yes, I did, it makes my page load MANY times faster! Commented Apr 23, 2013 at 8:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.