Karem
Karem

Reputation: 18103

Reverse array in php

array(7) {
  [0]=> array(2) { ["id"]=> string(1) "9"  ["roi"]=> float(0)    }
  [1]=> array(2) { ["id"]=> string(1) "1"  ["roi"]=> float(0)    }
  [2]=> array(2) { ["id"]=> string(2) "10" ["roi"]=> float(0)    }
  [3]=> array(2) { ["id"]=> string(2) "14" ["roi"]=> float(0)    }
  [4]=> array(2) { ["id"]=> string(1) "4"  ["roi"]=> float(0)    }
  [5]=> array(2) { ["id"]=> string(1) "5"  ["roi"]=> float(141)  }
  [6]=> array(2) { ["id"]=> string(1) "6"  ["roi"]=> float(2600) }
}

I would just like to reverse this, so id 6 (with roi of 2600) comes first in the array etc.

How can I do this? array_reverse() and rsort() does not work in this case

Upvotes: 6

Views: 19857

Answers (6)

Ninh Mạnh Dũng
Ninh Mạnh Dũng

Reputation: 1

It's easy. May be use usort function of php like:

usort($arr, function($a, $b) {    
  return $b['roi'] - $a['roi'];    
});

Just swap position $a and $b that is correct.

Upvotes: 0

sumon cse-sust
sumon cse-sust

Reputation: 454

$res = array(
    0=>array("id"=>9, "roi"=>0),
    1=>array("id"=>1,"roi"=>0),
    2=>array("id"=>10,"roi"=>0),
    3=>array("id"=>14,"roi"=>0),
    4=>array("id"=>4,"roi"=>0),
    5=>array("id"=>5,"roi"=>141),
    6=>array("id"=>6,"roi"=>2600));
    $count = count($res);

    for ($i=0, $j=$count-1; $i<=floor($count/2); $i++, $j--) {
        $temp = $res[$j];
        $res[$j] = $res[$i];
        $res[$i] = $temp;
    }
    echo '<pre>';
    print_r($res);
    echo '</pre>';

Upvotes: 0

railsbox
railsbox

Reputation: 888

$res = array(
    0=>array("id"=>9, "roi"=>0),
    1=>array("id"=>1,"roi"=>0),
    2=>array("id"=>10,"roi"=>0),
    3=>array("id"=>14,"roi"=>0),
    4=>array("id"=>4,"roi"=>0),
    5=>array("id"=>5,"roi"=>141),
    6=>array("id"=>6,"roi"=>2600));

$res4   =   array(); 
$count  = count($res);

for($i=$count-1;$i>=0;$i--){
    $res4[$i] =$res[$i]; 
}

print_r($res4);

Upvotes: 1

user933791
user933791

Reputation: 381

foreach($array as $arr){

  array_unshift($array, $arr); 
  array_pop($array);

}

Upvotes: 1

PeeHaa
PeeHaa

Reputation: 72662

http://php.net/manual/en/function.array-reverse.php:

$newArray = array_reverse($theArray, true);

The important part is the true parameter, which preserves the keys.

Not convinced? You can see it in action on this codepad exampole.

Upvotes: 24

Bram
Bram

Reputation: 1112

You can use an usort() function, like so

$arr = array('......'); // your array
usort($arr, "my_reverse_array");

function my_reverse_array($a, $b) {
    if($a['roi'] == $b['roi'])
    {
        return 0;
    }
    return ($a['roi'] < $b['roi']) ? -1 : 1;
}

This will make sure the item with the highest roi is first in the array.

Upvotes: 0

Related Questions