-1

I'm loading a json file where there's an object data, which has properties that are only integers.

They begin with 1000 then increment until 9999. Everything is ok. The problem comes with the properties 10000 and higher. When I load the file using json_decode(file_get_contents('myjsonfile')), if I try to do a foreach loop I have all the properties that begin with 1000 first, so this includes all the properties 10000 then I have other ones (2000, 3000, and so on).

The actual problem is that I need to keep the keys (because the properties are objects that sometimes contain link to keys of the "base" data object).

How can you make a working foreach loop with keys ordered asc?

Olivier Pons
  • 13,972
  • 24
  • 98
  • 190
  • So you are sorting array keys as strings. Sort it as integers, so 10000 comes after 9999. – Justinas Dec 30 '14 at 12:00
  • I dont want to sort it, it just want to make a foreach on it. – Olivier Pons Dec 30 '14 at 12:01
  • Are you using `foreach($array as $key => $value)` or `foreach($array as $value){ $index++ }`? – Justinas Dec 30 '14 at 12:02
  • That's what I'm saying: if I do a `foreach($array as $key => $value)` I begin with 1000, 1001, then 10001, 10002, then 2000, 2001. I want to have: 1000, 1001, 2000, 2001, then 10001, 10002 – Olivier Pons Dec 30 '14 at 12:05

2 Answers2

0

I did this using a temporary table to sort key with SORT_NATURAL then foreach on it:

$tmp=array();
foreach ($obj as $key=>$item) {
    $tmp[$key]=$item;
}
$tmp=(array_keys($tmp));
sort($tmp, SORT_NATURAL);
foreach ($tmp as $key) {
    $item=$obj->$key;
    /* ... my other code, with a good iteration ... */
}
Olivier Pons
  • 13,972
  • 24
  • 98
  • 190
0

Since JSON array keys are strings, that's why you get array sorted automatically.

Use ksort function first:

$array = (array) json_decode(json_encode(array("3000" => "Third", "10000" => "Fourth", "2000" => 'Second', "1000" => 'First')));

ksort($array, SORT_NUMERIC);

foreach ($array as $k => $v) {
    var_dump($k, $v); echo "<br/>";
}
Justinas
  • 34,232
  • 3
  • 56
  • 78
  • You could write the full JSON string in json_decode() so you dont go through json_encode(), which might change the result. – Olivier Pons Dec 30 '14 at 12:25
  • @OlivierPons You do not provided any JSON string, so I created you in ugly useless way. You can replace it with your JSON array. – Justinas Dec 30 '14 at 12:36