A
A
aornos2015-06-03 15:51:12
PHP
aornos, 2015-06-03 15:51:12

Php sort array parent-child?

Hello
The database stores a multi-level menu with products, in a table of the form:
(itemId, parentId, itemtitle, ...)
A menu is built on this table, using a recursive function, ordered and nested (ul-li)
You need to build an html select on it for the form in the admin.
Data from the database comes out of order, using array_multisort they can be sorted in ascending order by itemId and parentId to the form:
(itemId - parentId - itemTitle)
1 - 0 - ***A
2 - 0 - ***B
3 - 0 - ** *C
4 - 0 - ***D
6 - 1 - ***E
7 - 1 - ***F
8 - 1 - ***G
9 - 2 - ***H
10 - 2 - ***I
11 - 2 - ***J
12 - 2 - ***K
13 - 2 - ***L
14 - 3 - ***M
15 - 3 - ***N
16 - 3 - ***O
17 - 4 - ***P
18 - 4 - ***Q
to me, for passing to json and so on. must be sorted by type:
1 - 0 - ***A
6 - 1 - ***E
7 - 1 - ***F
8 - 1 - ***G
2 - 0 - ***B
9 - 2 - * **H
10 - 2 - ***I
11 - 2 - ***J
12 - 2 - ***K
13 - 2 - ***L
3 - 0 - ***C
14 - 3 - *** M
15 - 3 - ***N
16 - 3 - ***O
4 - 0 - ***D
17 - 4 - ***P
18 - 4 - ***Q
Accordingly, this is the question, how?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
aornos, 2015-06-06
@aornos

Actually the decision. I don’t pretend to be original, it only works for a two-level menu:

//получаем список категорий из каталога
    $items = $cataloAR->query("SELECT itemId, parentId,itemTitle FROM `catalog` ORDER BY parentId, itemId"); 
//сортируем предварительно по itemId, parentId
    $ids = array();//массив для идентификаторов
    $parents = array();//массив для родителей
// получаем список столбцов
    foreach ($items as $key => $row) {
        $ids[$key]  = $row['itemId'];
        $parents[$key] = $row['parentId'];
    }
// сортируем по возрастанию id, по возрастанию parent
    array_multisort($ids, SORT_ASC, $parents, SORT_ASC, $items);
//Создаем пустой массив для отсортированных данных типа - $entryList['itemId']['itemTitle'] 
    $entryList = array();//пустой массив
    $len = count($items); //получаем общее кол-во элементов для обработки
    $currentEntry = 0;  //номер текущего элемента
//итерируем
//пока не достигли последнего элемента в списке
   while($currentEntry < $len){        
//если нет текущего эл-то то переходим к следующему
        if (!isset($items[$currentEntry])) {
            $currentEntry++;
        } 
 //берем текущий эл-т из $items
//кладем его в $entryList
        $entryList[] = $items[$currentEntry];    
// запоминаем текущий  id 
        $currentId = $items[$currentEntry]['itemId'];        
//убираем эл-т из  $items, тк мы его уже положили в отсортированный список
        unset($items[$currentEntry]);     
//Ищем в $items записи с  patternId = $items['itemId']  
//ищем где  такой-же родитель, кладем в отсортированный список
//удаляем эл-т который забрали 
        foreach ($items as $key => $value) {
            if($value['parentId'] == $currentId){
                $entryList[] = $value;               
                unset($items[$key]);                  
            } 
            if (!isset($value)){
                continue;
            }
            
        } 
//увеличиваем счетчик               
            $currentEntry++;                   
    }    
//очищаем отсортированный массив от пустых эл-тов $entryList
    $sortedList = array_filter($entryList);
 //Enjoy it!
    return $sortedList;

H
He11ion, 2015-06-03
@He11ion

php.net/manual/ru/function.usort.php and inside the function you already compare what you want

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question