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

查看:45
本文介绍了在 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天全站免登陆