我有一些数组,我想将它们合并为一个,只使用一次,这是我的数组:
["ar1"]
["ar2"]
["ar2"]
["ar3"]
["ar4","ar2","ar5"]
["ar6","ar1"]
["ar5","ar3","ar7"]
["ar8","ar9","ar7"]
["ar3"]
我希望它返回:
AR1,AR2,AR3,AR4,AR5,AR6,AR7,AR8,AR9
在PHP中有一种简单的方法吗?
答案 0 :(得分:-1)
这是你可以做到的:
$input = [
["ar1"],
["ar2"],
["ar2"],
["ar3"],
["ar4","ar2","ar5"],
["ar6","ar1"],
["ar5","ar3","ar7"],
["ar8","ar9","ar7"],
["ar3"],
];
if ($input) {
$merged = call_user_func_array('array_merge', $input);
$unique = array_unique($merged);
$final = array_values($unique);
} else {
$final = [];
}
print_r($final);
输出看起来像这样:
Array
(
[0] => ar1
[1] => ar2
[2] => ar3
[3] => ar4
[4] => ar5
[5] => ar6
[6] => ar7
[7] => ar8
[8] => ar9
)
一些笔记重新编码:
$merged
- 这基本上将输入数组中的所有项合并为单个数组。当零输入数组时,我们需要if
来处理琐碎的情况(在这种情况下array_merge
将失败)。
$unique
- 此处我们删除所有重复项。
$final
- 但array_unique
也使用数组键(而不是0,1,2,你可以得到5,7,12,即非连续索引),所以,我们应该整理钥匙。这是可选步骤,具体取决于您可能跳过它的任务。如果跳过此步骤(查看键),输出的外观如下:
Array
(
[0] => ar1
[1] => ar2
[3] => ar3
[4] => ar4
[6] => ar5
[7] => ar6
[11] => ar7
[12] => ar8
[13] => ar9
)