带有指向前一块的嵌入块的PHP数组
我正在尝试将以下阵列与指向前一个阵列的每个阵列合并,如果存在重复,它将构建一个嵌入式阵列,请参见我想要的阵列: 阵列:带有指向前一块的嵌入块的PHP数组,php,arrays,Php,Arrays,我正在尝试将以下阵列与指向前一个阵列的每个阵列合并,如果存在重复,它将构建一个嵌入式阵列,请参见我想要的阵列: 阵列: array ('test.php'), array ('test', 'test.php'), array ('test', 'test1'), array ('test', 'test1', 'test1.php'), array ('test', 'test.php'), array ('test', 'test2', 'test2.php'), array ('test'
array ('test.php'),
array ('test', 'test.php'),
array ('test', 'test1'),
array ('test', 'test1', 'test1.php'),
array ('test', 'test.php'),
array ('test', 'test2', 'test2.php'),
array ('test', 'test2', 'test3.php'),
array ('test', 'test2', 'test4.php')
所需阵列:
Array
(
[0] => test.php
[1] => Array
(
[test] => Array
(
[0] => test.php
[1] => Array
(
[test1] => Array
(
[0] => test1.php
)
)
[2] => test.php
[3] => Array
(
[test2] => Array (
[0] => test2.php
[1] => test3.php
[2] => test4.php
)
)
)
)
)
我感谢任何人能够提前提供的帮助。如果我假设您的源数组总是从根到值排序,我可以为您提供以下解决方案
<?php
function merge (array $src, array $dst) {
if (!$src || empty($src)) {
return $dst;
}
$tempDst = &$dst;
foreach ($src as $srcItem) {
$itemIsSet = false;
if (preg_match('/(.php)/', $srcItem)) {
$tempDst[] = $srcItem;
continue;
}
foreach ($tempDst as $key => $value) {
if (is_array($value) && isset($value[$srcItem])) {
$tempDst = &$tempDst[$key][$srcItem];
$itemIsSet = true;
break;
}
}
if (!$itemIsSet) {
array_push($tempDst, array(
$srcItem => array()
));
$last = array_key_last($tempDst);
$tempDst = &$tempDst[$last][$srcItem];
}
}
return $dst;
}
$source = array(
array ('test0.php'),
array ('test', 'test.php'),
array ('test', 'test1'),
array ('test', 'test1', 'test1.php'),
array ('test', 'test2', 'test2.php'),
array ('test', 'test2', 'test3.php'),
array ('test', 'test2', 'test4.php'),
);
$destination = array();
foreach ($source as $array) {
$destination = merge($array, $destination);
}
?>
<pre>
<?= print_r($destination); ?>
</pre>
可以有多于或少于4个阵列吗?所有数组是同时生成的,还是在一个循环中生成的?查看生成数组的代码将有助于给出最佳答案。是的,数组的数量可以是无限的。我基本上是在创建一个站点地图,所以我使用了多个文件的URL,并使用explode将它们拆分为各个部分。然后我希望前面的目录指向目录中的所有文件。数组是在我循环遍历每个文件并分解其部分时创建的。这太棒了。然而,我犯了一个错误。是否可以将输出改为如下所示<代码>数组([0]=>test.php[1]=>Array([test]=>Array([0]=>test.php[1]=>Array([test1]=>test1.php[1]=>test.php[2]=>Array([test2]=>Array([0]=>test2.php[1]=>test3.php[2]=>test4.php(()))))您的意思是应该订购物品吗?否,您能看到我编辑的问题吗?我决定在数组中循环,如果键不是数字,我就把它放在一个数组中。然后我把每一块放回一个新的阵列。谢谢您的帮助。@Dustin-以防万一我为了产生所需的输出而更改了代码
Array
(
[0] => test0.php
[1] => Array(
[test] => Array(
[0] => test.php
[1] => Array(
[test1] => Array(
[0] => test1.php
)
)
[2] => Array(
[test2] => Array(
[0] => test2.php
[1] => test3.php
[2] => test4.php
)
)
)
)
)