我有多个数组并希望合并它们,但是,只有在巧合时合并。假设以下示例:
[82] => Array(
[0] => 72
[1] => 85
[2] => 86
[3] => 104
[4] => 218
[5] => 219
)
[85] => Array(
[0] => 194
)
[72] => Array(
[0] => 98
[1] => 99
[2] => 195
)
[104] => Array(
[0] => 105
)
我需要这个:
[82] => Array(
[72] => Array(
[0] => 98
[1] => 99
[2] => 195
)
[85] => Array(
[0] => 194
)
[2] => 86
[104] => Array(
[0] => 105
)
[4] => 218
[5] => 219
)
我有4个一维数组,现在,我只有1个多维数组。
我该怎么办?
答案 0 :(得分:0)
为您的需求写了一个简单的功能。注意函数&中的参考。 foreach循环在这里真的很有帮助。这将合并您想要的样式中的数组,但每次都会合并它(意味着1个数组可以转到多个数组)。如果要删除添加的数组,请查看帖子的末尾。
function merge_myway($array, &$depth) {
foreach($depth as $key => &$value)
{
if(is_array($value))
merge_myway($array, $value);
else
{
if(array_key_exists($value, $array))
{
$value = array($value => $array[$value]);
}
}
}
}
$array = [
82 => array(
0 => 72,
1 => 85,
2 => 86,
3 => 104,
4 => 218,
5 => 219,
),
85 => array(
0 => 194,
),
72 => array(
0 => 98,
1 => 99,
2 => 195,
),
104 => array(
0 => 105,
),
];
echo "<pre>";
print_r($array);
merge_myway($array, $array);
print_r($array);
echo "</pre>";
合并后销毁数组的功能:
function merge_myway(&$array, &$depth) {
foreach($depth as $key => &$value)
{
if(is_array($value))
merge_myway($array, $value);
else
{
if(array_key_exists($value, $array))
{
$temp = $array[$value];
unset($array[$value]);
$value = array($value => $temp);
}
}
}
}