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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 关于#matlab#的问题:有没有什么其他办法能够保证不退出进程(相关搜索:matlab调用)
    • ¥15 依据报错在原代吗格式的基础上解决问题
    • ¥15 在虚拟机中安装flash code
    • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
    • ¥20 verilog状态机方法流水灯
    • ¥15 pandas代码实现不了意图
    • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
    • ¥25 LT码在高斯信道下的误码率仿真
    • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
    • ¥15 yolov5目标检测并显示目标出现的时间或视频帧