原始数组如下所示:
$array = array(
array(
'key' => 'key1',
'val' => 'val1'
),
array(
'key' => 'key2:subkey1',
'val' => 'val2'
),
array(
'key' => 'key3:subkey2',
'val' => 'val3'
),
array(
'key' => 'key3:subkey3:subsubkey1',
'val' => 'val4'
),
array(
'key' => 'key3:subkey3:subsubkey2',
'val' => 'val5'
),
array(
'key' => 'key3:subkey3:subsubkey3',
'val' => 'val6'
)
);
我想在原来的阵列的基础上生成一个新的阵列,看起来像这样:
$result = array(
'key1' => 'val1',
'key2' => array(
'subkey1' => 'val2'
),
'key3' => array(
'subkey2' => 'val3',
'subkey3' => array(
'subsubkey1' => 'val4',
'subsubkey2' => 'val5',
'subsubkey3' => 'val6'
)
)
);
该算法应该能够处理任何深度的参考阵列。到目前为止,我已经尝试过了,但由于各种原因,我对使用eval
不满意:
function convert($array) {
$out = array();
foreach ($array as $data) {
$key = $data['key'];
$pos = strpos($key, ':');
if ($pos === false) {
$out[$key] = $data['val'];
} else {
$split = explode(":", $key);
eval("$out['" . implode("']['", $split) . "'] = '" . $data['val'] . "';");
}
}
return $out;
}
有没有一种方法可以在不使用eval
的情况下解决这个问题,即直接设置$out
?val
来自用户输入,因此在这种情况下使用eval
显然是非常不安全的。
谢谢你的建议。
function convert($array) {
$out = array();
foreach ($array as $data) {
$key = $data['key'];
$value = $data['val'];
$helper = &$out;
foreach (explode(':', $key) as $i) {
$helper = &$helper[$i];
}
$helper = $value;
}
return $out;
}
我花了一段时间才弄清楚如何做到这一点。参考文献可能是实现这一点的最佳方式。
$helper
-变量是对$out
-数组的临时引用,我们希望在完成后返回。它用冒号分隔每个键作为分隔符,并遍历每个单独的键。在每次迭代中,我们都会将helper引用更改为下一个键。
一个例子:
$out = array();
explode(':', $key) => array('key3', 'subkey3', 'subsubkey1');
$helper = &$out;
// foreach loop starts
$helper = $helper['key3']; // Iteration 1
$helper = $helper['key3']['subkey3']; // Iteration 2
$helper = $helper['key3']['subkey3']['subsubkey1']; // Iteration 3
我希望你了解它是如何工作的。
试试这个简洁的代码:
$array = array(
array(
'key' => 'key1',
'val' => 'val1'
),
array(
'key' => 'key2:subkey1',
'val' => 'val2'
),
array(
'key' => 'key3:subkey2',
'val' => 'val3'
),
array(
'key' => 'key3:subkey3:subsubkey1',
'val' => 'val4'
),
array(
'key' => 'key3:subkey3:subsubkey2',
'val' => 'val5'
),
array(
'key' => 'key3:subkey3:subsubkey3',
'val' => 'val6'
)
);
$new_array = array();
foreach($array as $element) {
$temp = &$new_array;
foreach(explode(':', $element['key']) as $key) {
$temp = &$temp[$key];
}
$temp = $element['val'];
}
unset($temp);
var_dump($new_array);