按NextPageID字段排序数组

时间:2011-01-31 18:02:47

标签: php sql mysql linked-list

我在数据库中有信息需要以奇怪的方式排序。我在下面有一个非常简化的版本。

我需要按照NEXTPAGEID列所指示的顺序使用PHP输出它们。有人告诉我只是循环遍历值,但我无法找出正确的方法来循环它们。

ID: 1; NEXTPAGEID: 3  
ID: 3; NEXTPAGEID: 118  
ID: 9; NEXTPAGEID: 10  
ID: 10; NEXTPAGEID: 515  
ID: 11; NEXTPAGEID: 12  
ID: 118; NEXTPAGEID: 9

所以我真正需要的顺序是

ID: 1, 3, 118, 9, 10, 515, (whatever the NEXTPAGEID of 515 is)

等。

4 个答案:

答案 0 :(得分:2)

这需要支持MySQL缺少的递归查询。

你可以这样模仿它:

SELECT @r := 1, @c := 0 -- the first id

SELECT  t.*
FROM    (
        SELECT  @r AS _current_id,
                @r :=
                (
                SELECT  nextpageid
                FROM    mytable
                WHERE   id = _current_id
                ) AS _next_id,
                @c := @c + 1 AS _orderer
        FROM    mytable t
        ) q
JOIN    mytable t
ON      t.id = q._current_id
ORDER BY
        _orderer

答案 1 :(得分:1)

SELECT * FROM `table_name` ORDER BY `NEXTPAGEID` ASC

答案 2 :(得分:0)

如果您不想进行递归SQL查询,可以使用PHP进行排序:

function sort_by_nextpageid($array) {

    $index = array();
    foreach($array as $row) $index[$row['ID']] = $row;

    $result = array();
    $id = 1;
    while (isset($index[$id])) {
        $result[] = $index[$id];
        $id = $index[$id]['NEXTPAGEID'];
    }

    return $result;
}

并调用这样的函数:

// rows from the db

$array = array(
    array('ID' => 1, 'NEXTPAGEID' => 3),
    array('ID' => 3, 'NEXTPAGEID' => 118),
    array('ID' => 9, 'NEXTPAGEID' => 10),
    array('ID' => 10, 'NEXTPAGEID' => 515),
    array('ID' => 11, 'NEXTPAGEID' => 12),
    array('ID' => 118, 'NEXTPAGEID' => 9),
);

$array = sort_by_nextpageid($array);

答案 3 :(得分:-1)

$query = "SELECT * FROM `table_name`";
$result = mysql_result($query);

if(mysql_num_rows($result)>0){
    while($rows=mysql_fetch_assoc($result)){
    $testArray[] = $rows[ID];
    $testArray[] = $rows[NEXTPAGEID];
}

$result2 = array_unique($result);
$lastArray=array_values($result2);