php sorts sample code for two dimensional arrays by the specified key value key

  • 2020-11-25 07:10:27
  • OfStack

 
function array_sort($array, $key){
if(is_array($array)){
$key_array = null;
$new_array = null;
for( $i = 0; $i < count( $array ); $i++ ){
$key_array[$array[$i][$key]] = $i;
}
ksort($key_array);
$j = 0;
foreach($key_array as $k => $v){
$new_array[$j] = $array[$v];
$j++;
}
unset($key_array);
return $new_array;
}else{
return $array;
}
}

PHP2 dimensional array key value sorting

In PHP, array_multisort() can be used to sort multiple arrays once, or to sort multi-dimensional arrays based on one or more dimensions. The associated key name remains the same, but the numeric key name is re-indexed. The input array is treated as the columns of a table and sorted by rows, and the first array is the primary array to be sorted. If the rows (values) in the array are the same, sort them by the size of the corresponding values in the next input array, and so on.

However, if the array to be sorted is a 2-dimensional array and needs to be sorted by the key value of the array, such as the following 2-dimensional array needs to be sorted by the key name of sort, then array_multisort() cannot be implemented directly:


$data[5] = array('volume' => 67, 'edition' => 2);
$data[4] = array('volume' => 86, 'edition' => 1);
$data[2] = array('volume' => 85, 'edition' => 6);
$data[3] = array('volume' => 98, 'edition' => 2);
$data[1] = array('volume' => 86, 'edition' => 6);
$data[6] = array('volume' => 67, 'edition' => 7);
//  Prepare the array to sort 
foreach ($data as $k => $v) {
  $edition[] = $v['edition'];
}
array_multisort($edition, SORT_ASC, $data);
print_r($data);

The output:


Array
(
  [0] => Array
    (
      [volume] => 86
      [edition] => 1
    )

  [1] => Array
    (
      [volume] => 67
      [edition] => 2
    )

  [2] => Array
    (
      [volume] => 98
      [edition] => 2
    )

  [3] => Array
    (
      [volume] => 85
      [edition] => 6
    )

  [4] => Array
    (
      [volume] => 86
      [edition] => 6
    )

  [5] => Array
    (
      [volume] => 67
      [edition] => 7
    )

)

In order not to destroy the original key, a sorting function was written to support only 2-dimensional arrays.


/**
*  Sort by the size of a key value in an array, only supported 2 Dimensional array 
* 
* @param array $array  Sort an array 
* @param string $key  The key value 
* @param bool $asc  The positive sequence 
* @return array  Sorted array 
*/
function arraySortByKey(array $array, $key, $asc = true) 
{
  $result = array();
  //  Sort out the array to sort 
  foreach ( $array as $k => &$v ) {
    $values[$k] = isset($v[$key]) ? $v[$key] : '';
  }
  unset($v);
  //  Sort the key values that need to be sorted 
  $asc ? asort($values) : arsort($values);
  //  Rearrange the original array 
  foreach ( $values as $k => $v ) {
    $result[$k] = $array[$k];
  }
 
  return $result;
}

Related articles: