Example of Implementation Method for Recursive Sorting of PHP Array

  • 2021-09-12 00:38:34
  • OfStack

This paper describes the implementation method of recursive sorting of PHP arrays with examples. Share it for your reference, as follows:


/**
 *  Recursion is based on a specific key Sort an array 
 * @param $data
 * @param string $orderKey
 * @param string $sonKey
 * @param int $orderBy
 * @return mixed
 */
function recursion_orderby($data, $orderKey = 'order', $sonKey = 'children', $orderBy = SORT_ASC)
{
  $func = function ($value) use ($sonKey, $orderKey, $orderBy) {
    if (isset($value[$sonKey]) && is_array($value[$sonKey])) {
      $value[$sonKey] = recursion_orderby($value[$sonKey], $orderKey, $sonKey, $orderBy);
    }
    return $value;
  };
  return array_orderby(array_map($func, $data), $orderKey, $orderBy);
}
$a = [
  [
    'order' => 0,
  ],
  [
    'order' => -1,
    'children' => [
      [
        'order' => 0,
      ],
      [
        'order' => -2,
        'children' => [
          ['order' => 0],
          ['order' => -1],
          ['order' => 1],
        ],
      ],
    ],
  ],
  [
    'order' => 2,
  ],
];
var_dump(recursion_orderby($a));
/**
 *  Output: 
array(3) {
 [0] =>
 array(2) {
  'order' =>
  int(-1)
  'children' =>
  array(2) {
   [0] =>
   array(2) {
    'order' =>
    int(-2)
    'children' =>
    array(3) {
     [0] =>
     array(1) {
      'order' =>
      int(-1)
     }
     [1] =>
     array(1) {
      'order' =>
      int(0)
     }
     [2] =>
     array(1) {
      'order' =>
      int(1)
     }
    }
   }
   [1] =>
   array(1) {
    'order' =>
    int(0)
   }
  }
 }
 [1] =>
 array(1) {
  'order' =>
  int(0)
 }
 [2] =>
 array(1) {
  'order' =>
  int(2)
 }
}
*/

Note: Here's array_orderby The method is described in detail in the previous article "Usage of php Custom 2D Array Sorting Function array_orderby"

PS: Here we recommend another demonstration tool about sorting for your reference:

Online animation demonstrates insert/select/bubble/merge/hill/quick sort algorithm process tool:
http://tools.ofstack.com/aideddesign/paixu_ys

For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: