开发者

Order Array by NextPageID field

开发者 https://www.devze.com 2023-02-07 22:51 出处:网络
I have info in a database that needs ordered in a weird way. I have a r开发者_StackOverflow社区eally simplified version below.

I have info in a database that needs ordered in a weird way. I have a r开发者_StackOverflow社区eally simplified version below.

I need them to be output using PHP in the order that is being dictated by the NEXTPAGEID column. Someone told me to just loop through the values but I just can't figure out the proper way to loop through them like this.

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

So the order I really need is

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

, etc.


This requires a support for recursive queries which MySQL lacks.

You could emulate it like this:

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


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


If you don't want to do recursive SQL queries, you can sort in 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;
}

And call the function like this:

// 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);


$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);
0

精彩评论

暂无评论...
验证码 换一张
取 消