Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

PHP多维数组,根据sort进行排序,每层都排,变为正序

$arr = [
            ['title' => '菜单一', 'sort' => 5, 'child' => []],
            [
                'title' => '菜单二',
                'sort'  => 4,
                'child' => [
                    ['title' => '菜单三', 'sort' => 10, 'child' => []],
                    ['title' => '菜单四', 'sort' => 9, 'child' => []],
                ],
            ],
            [
                'title' => '菜单五',
                'sort'  => 3,
                'child' => [
                    ['title' => '菜单六', 'sort' => 7, 'child' => []],
                    ['title' => '菜单七', 'sort' => 6, 'child' => [
                        ['title' => '菜单七', 'sort' => 10, 'child' => [],
                        ['title' => '菜单七', 'sort' => 9, 'child' => []                ]],
                ],
            ]
        ];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
function callback_sort($itemA, $itemB)
{
    $sortA = array_key_exists('sort', $itemA) ? $itemA['sort'] : 0;
    $sortB = array_key_exists('sort', $itemB) ? $itemB['sort'] : 0;
    
    return ($sortA < $sortB) ? -1 : 1;
}
function tree_sort(& $arr)
{
    if(is_array($arr) === false)
        return;
        
    if(array_key_exists('child', $arr) === true && is_array($arr['child']) === true && count($arr['child']) > 0)
        tree_sort($arr['child']);
    
    usort($arr, callback_sort);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...