-1

How can i order associative array by value recursively. I have the key called "order" and numeric value with which i would like to order the array. Here is an example.

array(

  "something_one" => array(
    "one" => "content sample",
    "two" => "content sample",
    "order" => 4
    "next" => NULL
  ), 
 "something_two" => array(
    "one" => "content sample",
    "two" => "content sample",
    "order" => 1
    "next" => array(
       "something_four" => array(
          "one" => "content sample",
          "two" => "content sample",
          "order" => 2
          "next" => NULL
        ), 
     )
  ),
 "something_three" => array(
    "one" => "content sample",
    "two" => "content sample",
    "order" => 3
    "next" => NULL
  )

);
woody180
  • 41
  • 7
  • Can you show an example of the output you're expecting? – Blackhole Nov 18 '19 at 13:37
  • i won't to sort it by 'order' value – woody180 Nov 18 '19 at 13:39
  • 2
    I get that. But you have a nested array (the key `something_four` in your example) and you're talking about recursive sort, so… Do you want to flatten the result, for instance? Just give the expected output of your example, please. – Blackhole Nov 18 '19 at 13:42
  • as result i wan't to have the same array but sorted. I think there must be the way to rebuild this array and build the sorted / ordered one – woody180 Nov 18 '19 at 13:49
  • Please refer to this question: https://stackoverflow.com/questions/2699086/how-to-sort-multi-dimensional-array-by-value – Verro Nov 18 '19 at 14:46

1 Answers1

0
function array_value_multisort(&$array, $key, $nextArrayKey) {
        $sorter=array();
        $ret=array();
        reset($array);
        foreach ($array as $ii => $va) {
            if (is_array($va[$nextArrayKey])) {
                array_value_multisort($va[$nextArrayKey], $key, $nextArrayKey);
            }
            $sorter[$ii]=$va[$key];
        }
        asort($sorter);

        foreach ($sorter as $ii => $va) {
            if (is_array($array[$ii][$nextArrayKey])) {
                array_value_multisort($array[$ii][$nextArrayKey], $key, $nextArrayKey);
            }
            $ret[$ii]=$array[$ii];
        }
        $array = $ret;
    }

I think i found the answer.

  1. First argument is the array you want to sort
  2. Second - the key of the value by which you going to make sorting
  3. And finally - under which key next level array is located

In my example (which was the question at the same time) it should look like this:

array_value_multisort($array, 'order', 'next');
woody180
  • 41
  • 7