Answer the question
In order to leave comments, you need to log in
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);
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
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));
foreach ($array as $key => &$item){
if (is_array($item)){
$item = mySort($item);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question