Home php Sorting a multidimensional array on the key and its value PHP

Sorting a multidimensional array on the key and its value PHP

Author

Date

Category

Hello, there was a question on arrays, or rather sorting it.
There is a multidimensional array of the form:

Return Array (
    Array (
      'name' = & gt; 'Home',
      'url' = & gt; 'http: //pegas-cms.localhost/',
      'num' = & gt; 0,
    ),
    Array (
      'name' = & gt; 'Blog',
      'url' = & gt; 'http: //pegas-cms.localhost/blog/',
      'num' = & gt; 0,
    ),
    Array (
      'name' = & gt; 'The list of questions',
      'url' = & gt; 'http: //pegas-cms.localhost/feedback/list',
      'num' = & gt; 0,
      'Child' = & gt; Array (
        Array (
          'name' = & gt; 'The list of questions',
          'url' = & gt; 'http: //pegas-cms.localhost/feedback/list',
          'tooltip' = & gt; 'The list of questions',
          'num' = & gt; 0,
      ),
        Array (
          'name' = & gt; 'Add question',
          'url' = & gt; 'http: //pegas-cms.localhost/feedback/themes/add',
          'num' = & gt; 0,
        ),
        Array (
          'name' = & gt; 'Search Question',
          'url' = & gt; 'http: //pegas-cms.localhost/feedback/search/? newsearch = 1',
          'num' = & gt; 0,
        ),
      ),
    ),
   );

How to sort the entire array to in the array at the very top there were arrays with the smallest NUM parameter
What are the options? Thank you


Answer 1, Authority 100%

usort
http://www.php.net/manual/ru/function.usort.php


Answer 2, Authority 100%

Sort it’s easy!

usort ($ array, function ($ a, $ b) {
  RETURN ($ A ['NUM'] - $ B ['num']);
});

Sign Dasified.


Answer 3, Authority 100%

As far as I understand the above answers with

return ($ a ['num'] - $ B ['num']);

Suitable only for keys with Integer values? Fore if I misunderstand the sorting.
For myself, wrote a simple feature working and with string values:

/ **
 * We sort the multidimensional array by the value of the nested array
 * @param $ Array Array Multidimensional Array Which Sort
 * @Param $ Field String The name of the field of the embedded array for which it is necessary to sort
 * @return Array Sorted Multidimensional Array
 * /
Function Custommultisort ($ Array, $ Field) {
  $ sortarr = array ();
  Foreach ($ Array AS $ Key = & GT; $ Val) {
    $ sortarr [$ Key] = $ Val [$ field];
  }
  array_multisort ($ sortarr, $ array);
  Return $ Array;
}

Please criticize essentially, and not to pour with different variations of the same, in documentation is and Other options.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions