排序数组 - 从外部数据中排序数组

时间:2013-04-23 07:59:11

标签: php arrays

我正在尝试根据SQL数据库中未排序的数组创建一个有序数组。

从数据库中获取的数据如下所示:

Array (
  //array ('name', position)
  array ('george', 2),
  array ('lenny' , 4),
  array ('rabbit', 1),
  array ('pet'   , 3)
)

我们的想法是对数组中的“名称”进行排序,其中position位于数组中。 我想最终成为:

Array ( 'rabbit', 'george', 'pet', 'lenny' )

我尝试过的当前方法是使用split_array()

$result是数据库中的数组。

foreach ( $result as $res ){
  $a = array(array($res['name'], $res['position']));
  array_splice($finalArray, ($res['position'] - 1), 0, $a);
}

问题有时取决于用户被检索的顺序,它不会正确排序,有没有更好的方法来做到这一点,或者这是好事,我做错了吗? 感谢。

1 个答案:

答案 0 :(得分:2)

使用uasort http://php.net/manual/en/function.uasort.php功能,您可以传递用户定义的比较function,如下所示:

$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
}

用法:

uasort( $myArray, 'myCompare' );

uasort操纵原始array

结果:

 var_dump($myArray);

 array(
       array('john',1),
       array('bill',3),
       array('joe',4)
 );

建议:

如果您可以修改SQL查询,最好使用ORDER BY指令缩短查询中的结果,如下所示:

 SELECT `name`,`position` 
 FROM `mytable`  #your table name
 WHERE 1  #or your conditions here
 ORDER BY `position` ASC  #ordering directive

这应该跑得更快。如果使用此功能,建议您将index添加到position字段。