无限分级
方法
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
$tree = array();
if (is_array($list)) {
$refer = array();
foreach ($list as $key => $data) {
$refer[$data[$pk]] =& $list[$key];
}
foreach ($list as $key => $data) {
$parentId = $data[$pid];
if ($root == $parentId) {
$tree[] =& $list[$key];
} else {
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
function list_sort_by($list, $field, $sortby = 'asc')
{
if (is_array($list)) {
$refer = $resultSet = array();
foreach ($list as $i => $data)
$refer[$i] = &$data[$field];
switch ($sortby) {
case 'asc':
asort($refer);
break;
case 'desc':
arsort($refer);
break;
case 'nat':
natcasesort($refer);
break;
}
foreach ($refer as $key => $val)
$resultSet[] = &$list[$key];
return $resultSet;
}
return false;
}
function list_search($list, $condition)
{
if (is_string($condition))
parse_str($condition, $condition);
$resultSet = array();
foreach ($list as $key => $data) {
$find = false;
foreach ($condition as $field => $value) {
if (isset($data[$field])) {
if (0 === strpos($value, '/')) {
$find = preg_match($value, $data[$field]);
} elseif ($data[$field] == $value) {
$find = true;
}
}
}
if ($find)
$resultSet[] = &$list[$key];
}
return $resultSet;
}
使用
$rules = M('rule')->order('sortid')->select();
$list = list_to_tree($rules, 'id', 'pid');
$this->assign('rules', $list);