2

I have to use a webservice which return JSON. After decode JSON I get array:

$arrays[0]["2013-04-09"]=$someValue;
$arrays[1]["2013-04-09"]=$someValue;
$arrays[2]["2013-04-11"]=$someValue;
$arrays[3]["2013-04-05"]=$someValue;
$arrays[4]["2013-04-09"]=$someValue;

I want sort (stable way and using key of second dim key) array and get as result:

$arrays[3]["2013-04-05"];
$arrays[0]["2013-04-09"]; //stable way don't swap with next val
$arrays[1]["2013-04-09"]; //stable way don't swap with next and prev vel
$arrays[4]["2013-04-09"]; //stable way, don't swap with prev val
$arrays[2]["2013-04-11"];

Can you help me? I try create own function of sort beacause ksort or krsort sort using only first dim key. Thank you for answers.

EDIT: I try write my own function - and this works - I got wrong "valid answers" in my units test and this is reason that I said that this isn't works:

private function getResult(){
...
usort($arrays,array($this,'mycmp'));
...
}
private function mycmp($a, $b){
    foreach($a as $key=>$val){
        $first = $key;
    }
    foreach($b as $key=>$val){
        $second = $key;
    }

    if ($first == $second){
        return 0;
    }
    return ($first < $second) ? -1:1;

}

THANKS FOR HELP

Bartosz Kowalczyk
  • 1,479
  • 2
  • 18
  • 34
  • What other keys does the structure have? If there's only one key (the date) in the sub-arrays, it should be fairly straightforward. Post some example JSON to help the answer along. – cmbuckley Apr 18 '13 at 12:03
  • I just had a perfect answer before realising your keys are different. Do you want to sort by key or by value of your second dimension? – ToBe Apr 18 '13 at 12:05
  • FYI: It'd be [this sort of approach](http://stackoverflow.com/questions/2477496/php-sort-array-by-subarray-value), but using the key rather than the value. Hence my question above. – cmbuckley Apr 18 '13 at 12:05

1 Answers1

0

Assuming that each of the sub-arrays has the date key in the same place (e.g. always first key in the object), you could do the following:

$keyPosition = 0; // location of the key in the array structures

usort($data, function ($a, $b) use ($keyPosition) {
    $aKeys = array_keys($a);
    $bKeys = array_keys($b);

    return strcmp($aKeys[$keyPosition], $bKeys[$keyPosition]);
});

However, what you should be aware is that PHP no longer supports stable sorting, so you may not get exactly the same ordering as previous. If this is an absolute requirement, you may need to roll your own sort function. Here's a Gist that might help.

cmbuckley
  • 40,217
  • 9
  • 77
  • 91