phplibrary/core/tabletree.php
2016-07-14 16:29:26 +03:00

69 lines
2.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Преобразование дерева из модели Plain в массив массивов (Adjacency List)
*/
require_once 'core/functions.php';
define (SORT_DESC, 0); // descending
define (SORT_ASC, 1); // ascending
/**
* Выбирает все сроки из таблицы с уникальными значениями ключа
* @param $name Имя ключа
* @param $table Двухмерный массив
* @example
* key_unique_values ('name', array (array ('name' => 1), array ('name' => 2), array ('name' => 1)))
=> array (1, 2)
* @end example
*/
function key_unique_values ($name, $table) {
// Ищем уникальные значения для заданного ключа
$keys = array ();
foreach ($table as $row) {
if (!in_array ($row[$name], $keys))
$keys[] = $row[$name];
}
return $keys;
}
/**
* Сортировка двумерного массива по заданному ключу
* @param $array Массив
* @param $key Имя ключа по значению которого будет идти сравнение
* @return Отсортированный массив
*/
function sortOn($array, $key, $fn = '__cmp') {
usort ($array, rcurry($fn, $key));
//usort ($array, create_function ('$x,$y', 'return __cmp ($x, $y, "'.$key.'");'));
return $array;
}
/**
* Обходит таблицу как дерево
* @param $level Array Уровни вложенности
* @param $table Таблица
* @param $fn Функция которая применяется к каждой ветке дерева
* $fn ($name, $index, $rows, $cc)
* @param $name Ключ уровня
* @param $index Значение ключа уровня
* @param $rows Все столбцы текущго уровня
* @parma $cc Столбцы более низкого уровня
*/
function tableTreeWalk($level, $table, $fn) {
if (empty ($level)) return $table;
$name = array_shift ($level);
$keys = key_unique_values($name, $table);
$data = array ();
foreach ($keys as $index) {
list($rows, $table) = partition (lcurry('__index', $index, $name), $table);
// $rows = array_filter ($table, lcurry('__index', intval($index), $name));
//$rows = array_filter ($table, create_function ('$x', 'return __index ('.intval($index).', \''.$name.'\', $x);'));
$data[$index] = call_user_func ($fn, $name, $index, $rows, tableTreeWalk ($level, $rows, $fn));
}
return $data;
}