我有这样的字符串:动态数组键
$string = 'one/two/three/four';
我把它变成一个数组:
$keys = explode('/', $string);
此阵列可具有任何数量的元素,如1- 1,2,5等
如何可以分配一个特定值到一个多维阵列中,但使用$keys
我创建从头确定要插入的位置?
像:
$arr['one']['two']['three']['four'] = 'value';
很抱歉,如果这个问题是混乱的,但我不知道该如何解释更好
我有这样的字符串:动态数组键
$string = 'one/two/three/four';
我把它变成一个数组:
$keys = explode('/', $string);
此阵列可具有任何数量的元素,如1- 1,2,5等
如何可以分配一个特定值到一个多维阵列中,但使用$keys
我创建从头确定要插入的位置?
像:
$arr['one']['two']['three']['four'] = 'value';
很抱歉,如果这个问题是混乱的,但我不知道该如何解释更好
这是一种不平凡的,因为你想窝,但它应该像这样:
function insert_using_keys($arr, $keys, $value){
// we're modifying a copy of $arr, but here
// we obtain a reference to it. we move the
// reference in order to set the values.
$a = &$arr;
while(count($keys) > 0){
// get next first key
$k = array_shift($keys);
// if $a isn't an array already, make it one
if(!is_array($a)){
$a = array();
}
// move the reference deeper
$a = &$a[$k];
}
$a = $value;
// return a copy of $arr with the value set
return $arr;
}
您需要首先确保密钥的存在,然后分配值。像这样的东西应该工作(未经测试):
function addValueByNestedKey(&$array, $keys, $value) {
$branch = &$array;
$key = array_shift($keys);
// add keys, maintaining reference to latest branch:
while(count($keys)) {
$key = array_pop($keys);
if(!array_key_exists($key, $branch) {
$branch[$key] = array();
}
$branch = &$branch[$key];
}
$branch[$key] = $value;
}
// usage:
$arr = array();
$keys = explode('/', 'one/two/three/four');
addValueByNestedKey($arr, $keys, 'value');
这是陈词滥调,但:
function setValueByArrayKeys($array_keys, &$multi, $value) {
$m = &$multi
foreach ($array_keys as $k){
$m = &$m[$k];
}
$m = $value;
}
$string = 'one/two/three/four';
$keys = explode('/', $string);
$arr = array(); // some big array with lots of dimensions
$ref = &$arr;
while ($key = array_shift($keys)) {
$ref = &$ref[$key];
}
$ref = 'value';
这是什么做的:
$ref
,跟踪对当前尺寸$arr
的引用。$keys
一次一个循环,它引用了当前参考的$key
元件。
这是行不通的。 '$ multi = $ multi [$ k]'创建一个* copy *,它不是一个引用,所以当你执行'$ multi = $ value'时,你实际上并没有修改任何东西,除了最后一个数组。 –
刚编辑它。 – MattoTodd
它*仍然*不会工作,你正在创建*副本*,而不是*引用*。 –