在PHP中动态创建/插入关联数组 [英] Dynamically creating/inserting into an associative array in PHP

查看:200
本文介绍了在PHP中动态创建/插入关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图动态地在PHP中建立一个关联数组,但并没有完全正确地制定我的策略.基本上,我想在数组结构的某个深度插入一个值,例如:

I'm trying to build an associative array in PHP dynamically, and not quite getting my strategy right. Basically, I want to insert a value at a certain depth in the array structure, for instance:

$array['first']['second']['third'] = $val;

现在,问题是,我不确定该深度是否可用,如果不能使用,我想为每个级别创建键(和数组),最后将值插入正确的级别

Now, the thing is, I'm not sure if that depth is available, and if it isn't, I want to create the keys (and arrays) for each level, and finally insert the value at the correct level.

由于我在代码中做了很多工作,所以我厌倦了执行一大堆"array_key_exists",所以我想做一个为我构建数组的函数,给定级别键的列表.对此有任何好的策略的帮助,我们将不胜感激.我敢肯定有一种非常简单的方法,我只是不明白...

Since I'm doing this quite a lot in my code, I grew tired of doing a whole bunch of "array_key_exists", so I wanted to do a function that builds the array for me, given a list of the level keys. Any help on a good strategy for this is appreciated. I'm sure there is a pretty simple way, I'm just not getting it...

推荐答案

如果这样做,php不会怪你

php doesn't blame you if you do it just so

$array['first']['second']['third'] = $val;
print_r($array);

如果您不想对密钥进行硬编码,这是一个灵活的解决方案

if you don't want your keys to be hard coded, here's a flexible solution

/// locate or create element by $path and set its value to $value
/// $path is either an array of keys, or a delimited string
function array_set(&$a, $path, $value) {
    if(!is_array($path))
        $path = explode($path[0], substr($path, 1));
    $key = array_pop($path);
    foreach($path as $k) {
        if(!isset($a[$k]))
            $a[$k] = array();
        $a = &$a[$k];
    }
    $a[$key ? $key : count($a)] = $value;
}

// example:
$x = array();

array_set($x, "/foo/bar/baz", 123);
array_set($x, "/foo/bar/quux", 456);
array_set($x, array('foo', 'bah'), 789);

这篇关于在PHP中动态创建/插入关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆