0

I have a 2D array in which first column holds page_id and second column holds points. The page_id is int value which corresponds to a page url in database and points refers to points allotted to that page.

I want to display pages such as way that pages with highest points display first and viceversa.

So Example if

arr[0][0] => 2

arr[0][1] => 200

arr[1][0] => 3

arr[1][1] => 29

arr[2][0] => 4

arr[2][1] => 400


----------------------
page_id    |     points
____________________
2           | 200

3           | 29

4           | 400

----------------------------------

Should be sorted as

----------------------
page_id    |     points
____________________
4           | 400

2           | 200

3           | 29

----------------------------------
Gopal Joshi
  • 2,350
  • 22
  • 49
  • 3
    What you have tried ? – Nambi Apr 18 '14 at 04:55
  • I'm not a regular on the PHP tag and not much of a PHP user, but surely, there are some sorting algorithm implementations in PHP out there, right? – Jules Apr 18 '14 at 04:56
  • How are you getting an array with the data in that very weird way? Maybe you can solve the issue way before you have to display it in a more efficient way. – Toote Apr 18 '14 at 05:04

2 Answers2

0

I would write my own sorting function that would use php asort() (http://php.net/asort).

Example:

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

aasort($your_array,"order");

See source here: https://stackoverflow.com/a/2699110/2335675

Please note that the $key or "order" is what key you want to sort by. So if you want to sort by [x][1] your key should be set to 1.

Community
  • 1
  • 1
Marcus Lind
  • 10,374
  • 7
  • 58
  • 112
0
$pageId = 0;
$points = 0;
for($i=0;$i<count($arr);$i++){
for($j = $i+1;$j< count($arr);$j++){
    if($arr[$i][1] < $arr[$j][1]){
        $pageId = $arr[$i][0];
        $points = $arr[$i][1];
        $arr[$i][0] = $arr[$j][0];
        $arr[$i][1] = $arr[$j][1];
        $arr[$j][0] = $pageId;
        $arr[$j][1] = $points;
    }
}
}

try this...it'll help.

Moax6629
  • 378
  • 4
  • 14