Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-如果键不存在,则添加到多维数组';不存在_Php_Arrays - Fatal编程技术网

PHP-如果键不存在,则添加到多维数组';不存在

PHP-如果键不存在,则添加到多维数组';不存在,php,arrays,Php,Arrays,很难理解如何解释它,所以代码可能会有所帮助 $out = array(); source_addValue($out['sources']['site1']['user_id'], '12345'); source_addValue($out['sources']['site1']['username'], 'testuser'); source_addValue($out['sources']['site1']['address']['state'], 'CA'); function so

很难理解如何解释它,所以代码可能会有所帮助

$out = array();

source_addValue($out['sources']['site1']['user_id'], '12345');
source_addValue($out['sources']['site1']['username'], 'testuser');
source_addValue($out['sources']['site1']['address']['state'], 'CA');

function source_addValue($field, $value) {
    global $out;
    if (!$field) $field = $value;
}
或者由于
$out['sources']
部分保持不变,可能类似于:

$out = array();

source_addValue('site1', 'user_id', '12345');
source_addValue('site1', 'username', 'testuser');
source_addValue('site1', array('address','state'), 'CA');

function source_addValue($site, $field, $value) {
    global $out;
    if (!$out['sources'][$site]$field) $out['sources'][$site]$field = $value;
}

无论如何,我都会被函数挂断,特别是
if
语句。我只需要能够检查该数组值是否已设置为
$out
(具有检查子数组的功能),如果未设置,请将其添加到
$out
数组中。

我不确定我是否理解您不需要的内容,但我猜:

function autoVivifyDynamicKeyPath($pathKeys, $val) {
    global $out;
    $cursor =& $out;
    foreach ($pathKeys as $key) {
        if (!isset($cursor[$key]) || !is_array($cursor[$key])) {
            $cursor[$key] = array();
        }
        $cursor =& $cursor[$key];
    }
    $cursor = $val;
}
autoVivifyDynamicKeyPath(array('site1', 'address', 'state'), 'ca');

Rambo的函数不检查当前键是否已设置。它覆盖所有已经有值的键。这里有一个修改过的版本,可以检查已经存在的密钥

$out = array();

source_addValue(array('sources', 'site1', 'user_id'), '12345');
source_addValue(array('sources', 'site1', 'username'), 'testuser');
source_addValue(array('sources', 'site1', 'address', 'state'), 'CA');

function source_addValue($pathKeys, $val) {
    global $out;
    foreach ($pathKeys as $key) {
        if (!isset($out[$key]) && !is_array($out[$key])) {
            $out[$key] = array();
        }
        $out =& $out[$key];
    }
    if(empty($out)){
        $out = $val;
    }
}

print_r($out);

可能重复这正是我要找的。非常感谢。