Dynamically creating/inserting into an associative array in PHP

心不动则不痛 提交于 2019-11-28 04:26:55

问题


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.

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...


回答1:


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);



回答2:


Create a function like:

function insert_into(&$array, array $keys, $value) {
     $last = array_pop($keys);       

     foreach($keys as $key) {
          if(!array_key_exists($key, $array) || 
              array_key_exists($key, $array) && !is_array($array[$key])) {
                  $array[$key] = array();

          }
          $array = &$array[$key];
     }
     $array[$last] = $value;
}

Usage:

$a = array();
insert_into($a, array('a', 'b', 'c'), 1);
print_r($a);

Ouput:

Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => 1
                )

        )

)



回答3:


That's tricky, you'd need to work with references (or with recursion, but I chose references here):

# Provide as many arguments as you like:
# createNestedArray($array, 'key1', 'key2', etc.)
function createNestedArray(&$array) {
    $arrayCopy = &$array;
    $args = func_get_args();
    array_shift($args);
    while (($key = array_shift($args)) !== false) {
        $arrayCopy[$key] = array();
        $arrayCopy = &$arrayCopy[$key];
    }
}



回答4:


<?php

function setElements(&$a, array $path = [], $values = [])
{

    if (!is_array($path)) {
        $path = explode($path[0], substr($path, 1));
    }

        $path = "[ '" . join("' ][ '", $path) . "' ]";
        $code =<<<CODE
        if(!isset(\$a{$path})){
            \$a{$path} = [];
        }
        return \$a{$path}[]  = \$values;
CODE;

        return eval($code);
}

$a = [];
setElements($a, [1,2], 'xxx');
setElements($a, [1,2,3], 233);
setElements($a, [1,2,4], 'AAA');
setElements($a, [1,2,3,4], 555);
print_r($a);

Output

Array
(
    [1] => Array
        (
            [2] => Array
                (
                    [0] => xxx
                    [3] => Array
                        (
                            [0] => 233
                            [4] => Array
                                (
                                    [0] => 555
                                )

                        )

                    [4] => Array
                        (
                            [0] => AAA
                        )

                )

        )

)

You should check it here http://sandbox.onlinephpfunctions.com/



来源:https://stackoverflow.com/questions/2447385/dynamically-creating-inserting-into-an-associative-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!