我想使用foreach循环自动将记录添加到新的关联数组中。我有一个数组,其中包含以下DOM元素的名称:
$DOM = array('element2','element22','element222','element2222');
和一个新的关联数组:
$NEW = array(
'element1' => '',
'element2' => '',
'element3' => array(
'element33' => array(
'element333' => ''
)
)
);
现在使用foreach循环会将新记录/数组添加到$ NEW数组:
foreach($DOM as $name){
//Do something
}
预期结果:
$NEW = array(
'element1' => '',
'element2' => array(
'element22' => array(
'element222' => array(
'element2222' => ''
)
)
),
'element3' => array(
'element33' => array(
'element333' => ''
)
)
);
你可以这样做吗?自动化这个过程?
答案 0 :(得分:0)
您可以通过将它们作为引用传递来修改foreach-loops中的数组:
foreach($array as &$value)
$value[] = $DOM
编辑:
<?php
$DOM = array('element2','element22','element222','element2222');
$NEW = array(
'element1' => '',
'element2' => '',
'element3' => array(
'element33' => array(
'element333' => ''
)
)
);
function insert(&$array, $ins) {
$element = array_shift($ins);
if($element == null) return;
foreach($array as $k => &$v) {
if($k === $element) {
$v[current($ins)] = '';
insert($v, $ins);
}
}
}
insert($NEW, $DOM);
var_dump($NEW);
答案 1 :(得分:0)
您可以使用array_push()
功能
检查这个mabe帮助:
$DOM = array('element2','element22','element222','element2222');
$NEW = array('element1' => '', 'element2' => '', 'element3' => array('element33' => array('element333' => '')));
array_push($NEW, $DOM);
print_r($NEW);
见这里:
php.net/manual/en/function.array-push.php
或在这里:
答案 2 :(得分:0)
如果我理解正确,$DOM
包含创建嵌套数组的键,最深层的空字符串值。所以你必须创建这样的数组:
$new_array = array();
$last = &$new_array;
foreach($DOM as $name){
$last[$name] = array();
$last = &$last[$name];
}
$last = '';
unset($last);
并以$NEW
递归合并:
$NEW = array_merge_recursive($NEW, $new_array);