php - Stable sort array using second dimension key -
i have use webservice return json. after decode json 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 , using key of second dim key) array , result:
$arrays[3]["2013-04-05"]; $arrays[0]["2013-04-09"]; //stable way don't swap next val $arrays[1]["2013-04-09"]; //stable way don't swap next , prev vel $arrays[4]["2013-04-09"]; //stable way, don't swap prev val $arrays[2]["2013-04-11"];
can me? try create own function of sort beacause ksort or krsort sort using first dim key. thank answers.
edit: try write own function - , works - got wrong "valid answers" in units test , reason said isn't works:
private function getresult(){ ... usort($arrays,array($this,'mycmp')); ... } private function mycmp($a, $b){ foreach($a $key=>$val){ $first = $key; } foreach($b $key=>$val){ $second = $key; } if ($first == $second){ return 0; } return ($first < $second) ? -1:1; }
thanks help
assuming each of sub-arrays has date key in same place (e.g. first key in object), following:
$keyposition = 0; // location of key in array structures usort($data, function ($a, $b) use ($keyposition) { $akeys = array_keys($a); $bkeys = array_keys($b); return strcmp($akeys[$keyposition], $bkeys[$keyposition]); });
however, should aware php no longer supports stable sorting, may not same ordering previous. if absolute requirement, may need roll own sort function. here's gist might help.
Comments
Post a Comment