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 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式