duanou9739 2016-03-24 15:01
浏览 74

PHP在方法中使用Closure将项目推送到嵌套数组

navigation.php

NavigationHelper::item('Main page', function($item) {
    $item->item('first sub-item', null);
    $item->item('second sub-item', function($item) {
        $item->item('third level sub');
    });
});

NavigationHelper.php

class NavigationHelper {

    protected $items = [];
    private static $_instance;

    public static function item($name, \Closure $children = null)
    {
        $c = static::_ini();

        $c->items[] = array(
            'name'  =>  $name,
            'childrens' => []//@todo
        );

        if ($children instanceof \Closure) {
            call_user_func($children, $c);
        }
    }

    protected static function _ini()
    {
        if (!static::$_instance) {
            static::$_instance = new static;
        }

        return static::$_instance;
    }
}

So i am trying to make a NavigationHelper class which pushes items in nested array using php closures. In navigation.php file i am adding item 'Main page' and his childrens should be 'first sub-item' and 'second sub-item' (last one should have 'third level sub').

Code above pushes all items to array, but i dont understand how to nest these childrens in to parents.

I tried to set index to created element and pass these index as parent id before calling closure function, but if children has children, it would overwrite this parent id and other childrens would go to sub-children...

$c->items[$c->index] = array(
    'name'  =>  $name,
    'parent'    =>  $c->parent
);
$c->index++;

if ($children instanceof \Closure) {
    $c->parent = $c->index;
    call_user_func($children, $c);
}

I would like some help that would solve my problem, is there is possibility to call callback functions with additional parameter (like current array index)? Maybe some other suggestions?

  • 写回答

0条回答 默认 最新

    报告相同问题?