尝试按一个键对PHP关联数组进行排序

I am trying to sort this associative array in PHP and none of the examples I have found worked.

The unsorted array is built so:

                //push into array
            $displayArray = array_push_assoc($displayArray, 'ContactID', $ContactID);
            $displayArray = array_push_assoc($displayArray, 'ContactFirstName', $ContactFirstName);
            $displayArray = array_push_assoc($displayArray, 'ContactLastName', $ContactLastName);
            $displayArray = array_push_assoc($displayArray, 'Ann_Desc', $CG_Desc);
            $displayArray = array_push_assoc($displayArray, 'DaysAway', $daysAway);

All I want to do is sort this array in ascending order by values associated with the 'DaysAway' key

I have tried this:

            function cmp($a, $b)
        {
            if ($a['DaysAway'] == $b['DaysAway']) {
                return 0;
            }

            return ($a['DaysAway'] < $b['DaysAway']) ? -1 : 1;
        }
        usort($displayArray, 'cmp');

        print_r($displayArray);
        print "<br>";

But all this does is seemingly randomly sorts the last row in the original array

Help is appreciated.

Remove all those array_push_assoc, since there's no function by that name.

Instead just put $displayArray['ContactID'] = $ContactID; and so on.

You should call usort on the parent array that contains each of these $displayArray entries, not the $displayArray itself.

Try using this function:

function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
  }
  asort($b);
  foreach($b as $key=>$val) {
        $c[] = $a[$key];
  }
  return $c;
}

$a would be the array you are sorting, while $subkey would be the field you want to sort by.