我有一个这样的字符串:
$string = 'one/two/three/four';
我把它变成一个数组:
$keys = explode('/', $string);
该阵列可以具有任意数量的元素,如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;
}
$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
元素 - 将值设置为最终引用
您需要首先确保键存在,然后分配值。像这样的东西应该有效(未经测试(:
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;
}
$arr['one']['two']['three']['four'] = 'value';
$string = 'one/two/three/four';
$ExpCheck = explode("/", $string);
$CheckVal = $arr;
foreach($ExpCheck AS $eVal){
$CheckVal = $CheckVal[$eVal]??false;
if (!$CheckVal)
break;
}
if ($CheckVal) {
$val =$CheckVal;
}
这将在数组中为u提供值。