PHP: Sort an array

 ̄綄美尐妖づ 提交于 2019-12-05 16:09:16

Don't do this in PHP!

The MySQL server is specificly designed to query AND sort data, read up on the MySQL "ORDER BY" syntax. Doing this on the MySQL server will save run-time, CPU Load and Memory Consumption.

Use php's uasort() function to define your own comparison function.

But using MySQL's sorting capabilities would be more appropriate, if it's possible in your case.

You want to sort it like it is in the DB, multilayered. I don't think uasort can help with this problem because you want to attach the children to the parent.

foreach ($arr as &$val) {
    $arr2[$val['id']] = &$val;
}

ksort($arr2);

foreach ($arr2 as $id => &$val) {
    $parent = $val['parent'];
    if ($parent == 0) {
        continue;
    }
    $arr2[$parent]['children'][$id] = &$val;
}

function flattenArrayByChildren($arr) {
    foreach ($arr as $id => $val) {
        if (isset($val['children'])) {
            $temp = flattenArrayByChildren($val['children']);
            unset($val['children']);
            $out[$id] = $val;
            $out = $out + $temp;
        } else {
            $out[$id] = $val;
        }
    }
    return $out;
}

$arr2 = array(1 => $arr2[1]);

$out = flattenArrayByChildren($arr2);

var_dump($out);

If you absolutely want to save the key, you can just add that to the $val in the first foreach, and retrieve it in the recursive function flattenArrayByChildren and use as key.

Problem solved - I made two simple functions. I hope other people could have use of this as well:

class data_comp
{
    var $fetched_tree = array();

    function tree_fetch($parent = 0)
    {
        $query = 'SELECT node.id, node.name, node.parent, (COUNT(parent.name) - 1) AS depth FROM test_competence AS node, test_competence AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt GROUP BY node.name ORDER BY node.name';
        $result = mysql_query($query) or die(mysql_error());
        $tree = array();

        while($data = mysql_fetch_assoc($result))
        {
            $tree[$data['parent']][$data['id']] = array('name' => $data['name'], 'depth' => $data['depth']);
        }

        $this->tree_print($tree, $parent);
    }

    function tree_print($tree, $parent)
    {
        foreach($tree[$parent] as $id => $value)
        {
            $this->fetched_tree[] = array('id' => $id, 'name' => $value['name'], 'depth' => $value['depth']);

            if(isset($tree[$id]) && is_array($tree[$id]))
            {
                $this->tree_print($tree, $id);
            }
        }
    }
}

Thank you for your time. Any improvements are more than welcome.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!