简体   繁体   中英

How to sort an Array based on value in PHP without breaking Array structure

I want to sort the array based on "match" index value as shown below:

Array
(
    [0] => Array
        (
            [U] => Array
                (
                    [user_id] => 10443
                    [match] => 100
                )

        )

)

This Array will be having match value like 25,50,75 etc.....

I tried below code but didn't worked :

function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
    $sort_col = array();
    foreach ($arr as $key=> $row) {
        $sort_col[$key] = $row['U'][$col];
    }
    return array_multisort($sort_col, $dir, $arr);
}

$a_sl =$this->array_sort_by_column($a_sl, 'match');

where $a_sl contains array structure mentioned above.

How to sort this array based on match without breaking the Array structure.

I use the following code to sort arrays by subvalues:

function array_sort_subval($a, $subkey) {

  if (!is_array($a) || count($a) == 0) {
    return $a;
  }

  $i = 0; // Required to work around items with the same subkey value
  foreach($a as $k=>$v) {
    $b[$v[$subkey] . $i] = $v;
    $i++;
  }

  ksort($b);

  foreach($b as $key=>$val) {
    $c[] = $val;
  }

  return $c;

}

To sort on deeper elements of your array, simply change the line

$b[$v[$subkey] . $i] = $v;

to get the deeper $subkey you want to sort on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM