我试图将数据插入到一个多维数组中,但这让我苦苦挣扎。我做不到。这让我很困惑。
我有一个"tree“数组:
$tree = array(
10 => array(),
11 => array(
4 => array(),
5 => array(),
6 => array()
)
);以及我必须用来插入数据的路径数组:
$path = array(11,5);结果应该是:
$tree = array(
10 => array(),
11 => array(
4 => array(),
5 => array($data),
6 => array()
)
);这必须适用于任何多维阵列(n维)。
需要注意的是,插入始终发生在树的最深分支之一。例如,如果树是一个三维数组,则path变量肯定会有3个值,并且插入操作将位于该数组可能具有的n个三维分支之一中。
我会在这里输入我所做的,但并不是那么多。我不知道我应该选择递归函数还是其他方式。
提前谢谢。
发布于 2019-06-21 20:18:27
嗯,你只需要一个递归函数,然后处理通过ref传递的数组,就像这样...
$tree = [
10 => [],
11 => [
4 => [],
5 => [],
6 => []
]
];
$path = [
11,
5,
0
];
var_dump(insertIntoArr($tree, 'Awesome value', $path, $tree));
function insertIntoArr(&$chunk, $data, $path, &$original) {
$key = array_shift($path);
if (!empty($path)) {
if (!isset($chunk[$key])) {
throw new \Exception('OMG! This path does\'t exists, I can\'t continue...');
}
return insertIntoArr($chunk[$key], $data, $path, $original);
}
$chunk[$key] = $data;
return $original;
}指纹。
array(2) {
[10]=>
array(0) {
}
[11]=>
array(3) {
[4]=>
array(0) {
}
[5]=>
array(1) {
[0]=>
string(13) "Awesome value"
}
[6]=>
array(0) {
}
}
}发布于 2019-06-21 20:29:57
方法1
您可以在foreach中使用pass by reference
$tree = [
10 => [],
11 => [
4 => [],
5 => [],
6 => []
]
];
$path = array(11,5,0);
$inseration = array('A','B');
$current = &$tree;
foreach($path as $key){
$current = &$current[$key];
}
$current = $inseration;
echo '<pre>';
print_r($tree);方法2
通过使用函数
$tree = [
10 => [],
11 => [
4 => [],
5 => 'r',
6 => []
]
];
$path = array(11,5);
$inseration = [1,2];
insertByKey($tree, $path, $inseration);
function insertByKey(&$array, $path, $inseration){
$current = &$array;
$key = array_shift($path);
while($key > 0){
$current = &$current[$key];
$key = array_shift($path);
}
$current = $inseration;
}发布于 2019-06-21 21:06:11
创建递归函数的另一个选择是存储一个类似于breadcrumb的数组,以跟踪当前路径的索引。然后将数组与路径数组进行比较,如果它们相等,则赋值。
function setByIndices(&$tree, $path, $data, $indices = []) {
foreach ($tree as $k => &$v) {
$indices[] = $k;
if ($indices === $path) {
$v = $data;
return;
}
if (is_array($v)) setByIndices($v, $path, $data, $indices);
array_pop($indices);
}
}
setByIndices($tree, $path, $data);https://stackoverflow.com/questions/56702776
复制相似问题