S
S
SerjNoob2018-08-16 17:55:26
PHP
SerjNoob, 2018-08-16 17:55:26

Could you, dear users, help with the php task?

sorting arrays of any nesting in ascending order, without using ready-made methods ( write your own method that will sort the array and all subarrays )
using sorting algorithms like quicksort, you can only sort the main array

function quicksort($arr){
    $lte = $gt = array();
    if(count($arr) < 2){
        return $arr;
    }
    $pivot_key = key($arr);
    $pivot = array_shift($arr);
    foreach($arr as $val){
        if($val <= $pivot){
            $lte[] = $val;
        } else {
            $gt[] = $val;
        }


    }
    return array_merge(quicksort($lte),array($pivot_key=>$pivot),quicksort($gt));
}
 

$arr = quicksort($arr);
var_dump($arr);

Well, there are also problems with an associative array, the third level of nesting does not sort by key
if (count($array))
        $temp_array[key($array)] = array_shift($array); // присваиваем первый эл массива ключу

    foreach($array as $key => $val){
        $offset = 0;
        $found = false;
        foreach($temp_array as $tmp_key => $tmp_val)
        {
            if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
            {
                $temp_array = array_merge(    (array)array_slice($temp_array,0,$offset),//сливаем кол-во массивов
                                            array($key => $val),
                                            array_slice($temp_array,$offset) //выбираем срез массива
                                          );
                $found = true;
            }
            $offset++;
        }
        if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
    }

    if ($sort_ascending) $array = array_reverse($temp_array); //возвращает массив с эл в обратном порядке

    else $array = $temp_array;
}

mySort($data , 'id'  );

var_dump($data);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dtBlack, 2018-08-17
@SerjNoob

As I understand it, sorting a single-level array does not cause difficulties for you?
So why not use a recursive call to such a function then? Especially in the first example, recursion is used.
A simple bubble method example would look like this:

function mySort($array){
    // перебираем массив
    for ($j = 0; $j < count($array) - 1; $j++){
        for ($i = 0; $i < count($array) - $j - 1; $i++){
            // если текущий элемент больше следующего
            if ($array[$i] > $array[$i + 1]){
                // меняем местами элементы
                $tmp_var = $array[$i + 1];
                $array[$i + 1] = $array[$i];
                $array[$i] = $tmp_var;
            }
        }
    }
    //Производим сортировку во вложенных массивах, по необходимости можно выполнить перед основной сортировкой
    foreach ($array as $key => &$item){
        if (is_array($item)){
            $item = mySort($item);
        }
    }
    return $array;
}
$arr = array(7,9,8,array(3,2,1),1,2,3,4,5,6);
print_r(mySort($arr));

Everything but the lines:
foreach ($array as $key => &$item){
        if (is_array($item)){
            $item = mySort($item);
        }
    }

is an implementation of the bubble method.
PS: to implement nested sorting, it is enough to slightly change the quicksort example, but I think the author will do it on his own...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question