-1

I have an array created like that :

$myarray = array();
$myarray['id1'] = array('pos' => 3, 'data' => '...');
$myarray['id2'] = array('pos' => 1, 'data' => '...');
$myarray['id3'] = array('pos' => 2, 'data' => '...');

I would like to iterate on $myarray with the order of the pos value. How can I do that ?

The only way I see for the moment is recreate a new ordered array from the first one. That's ugly, of course...

EDIT: This is not a duplicate of this question. I want to keep the keys linked to my subarrays.

Community
  • 1
  • 1
Caduchon
  • 4,574
  • 4
  • 26
  • 67

2 Answers2

3

You can use uasort http://php.net/manual/en/function.uasort.php

to define custom sort functions:

uasort($myarray, "mySortFunction");

function mySortFunction($a, $b){
  return $a["pos"] - $b["pos"]; //or $b - $a, depending on desired order
}
dognose
  • 20,360
  • 9
  • 61
  • 107
2

You can use uasort to save keys

$myarray['id1'] = array('pos' => 3, 'data' => '...');
$myarray['id2'] = array('pos' => 1, 'data' => '...');
$myarray['id3'] = array('pos' => 2, 'data' => '...');

uasort ($myarray, function($it1, $it2) { return $it1['pos'] - $it2['pos']; });
var_dump($myarray);

array(3) {
  ["id2"]=>
  array(2) {
    ["pos"]=>
    int(1)
    ["data"]=>
    string(3) "..."
  }
  ["id3"]=>
  array(2) {
    ["pos"]=>
    int(2)
    ["data"]=>
    string(3) "..."
  }
  ["id1"]=>
  array(2) {
    ["pos"]=>
    int(3)
    ["data"]=>
    string(3) "..."
  }
}
splash58
  • 26,043
  • 3
  • 22
  • 34
  • This solution is very nice. I would like to accept it, but it doesn't work on one of my workstations with a too old version of php (5.2.17). The solution of dognose is more general. – Caduchon Jun 07 '15 at 18:07
  • @Caduchon No problem :) Moreover, it is the same – splash58 Jun 07 '15 at 19:10