我有一个这样的字符串:
$string = 'one/two/three/four';
我把它变成一个数组:
$keys = explode('/', $string);
此数组可以包含任意数量的元素,如1,2,5等。
如何为多维数组指定某个值,但是使用我在上面创建的$keys
来确定要插入的位置?
像:
$arr['one']['two']['three']['four'] = 'value';
很抱歉,如果问题令人困惑,但我不知道如何更好地解释
答案 0 :(得分:14)
这是非常重要的,因为你想要嵌套,但它应该是这样的:
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;
}
答案 1 :(得分:6)
$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
元素。答案 2 :(得分:1)
您需要首先确保密钥存在,然后分配值。这样的事情应该有效(未经测试):
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');
答案 3 :(得分:1)
这是老生常谈但是:
function setValueByArrayKeys($array_keys, &$multi, $value) {
$m = &$multi
foreach ($array_keys as $k){
$m = &$m[$k];
}
$m = $value;
}
答案 4 :(得分:0)
$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;
}
这将为您提供数组中的值。