doufen3563 2014-11-23 17:56
浏览 13
已采纳

php multi array动态创建

I have q question: what is the easiest way to create multi-dimensional array in php dynamically?

Here a static version:

$tab['k1']['k2']['k3'] = 'value';

I would like to avoid eval()
I'm not successful with variable variable ($$)
so I'm trying to develop a function fun with such interface:

$tab = fun( $tab, array( 'k1', 'k2', 'k3' ), 'value' );

Do you have a solution? What is the simplest way?

regards, Annie

  • 写回答

3条回答 默认 最新

  • dongnanke4106 2014-11-23 19:04
    关注

    There are a number of ways to achieve this, but here is one which uses PHP's ability to have N arguments passed to a function. This gives you the flexibility of creating an array with a depth of 3, or 2, or 7 or whatever.

    // pass $value as first param -- params 2 - N define the multi array
    function MakeMultiArray()
    {
        $args = func_get_args();
        $output = array();
        if (count($args) == 1)
            $output[] = $args[0]; // just the value
        else if (count($args) > 1)
        {
            $output = $args[0];
            // loop the args from the end to the front to make the array
            for ($i = count($args)-1; $i >= 1; $i--)
            {
                $output = array($args[$i] => $output);
            }
        }
        return $output;
    }   
    

    Here's how it would work:

    $array = MakeMultiArray('value', 'k1', 'k2', 'k3');
    

    And will produce this:

    Array
    (
        [k1] => Array
            (
                [k2] => Array
                    (
                        [k3] => value
                    )
            )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?