所以这是我的代码:
$array = [];
$array[44259] = [50007, 50009, 46372];
$array[50007] = [50008];
$array[50009] = [50010];
$array[46372] = [46418, 46419, 46421];
$array[46421] = [146880];
如您所见,这是一个我设置值和键的数组。
我想"合并"它们在一起所以不应该看起来像它,它应该是这样的:
$array[44259] = [50007, 50009, 46372, 50008, 50010, 50010, 46419, 46421, 146880];
这只是"代码"代表我想要的样子。
我已经尝试过了:
foreach($array as $cid => $pid){
foreach($pid as $pip){
if(isset($array[$pipp])){
foreach($array[$pipp] as $pip){
$array[$cid][] = $pip;
unset($array[$pipp]);
}
}
}
}
但是它给了我这个回复:
[44259] => Array([0] => 50007 [1] => 50009 [2] => 46372 [3] => 50008 [4] => 50010 [5] => 46418 [6] => 46419 [7] => 46421 )
[46372] => Array([0] => 146880)
我知道这很容易,但我的思维很慢,无法想办法。
答案 0 :(得分:1)
你想尝试合并
> gdb -n -tui filename
答案 1 :(得分:1)
您可以使用array_keys()
和reset()
获取第一个密钥。然后,您可以将所有数组的值添加到此键:
$array = [];
$array[44259] = [50007, 50009, 46372];
$array[50007] = [50008];
$array[50009] = [50010];
$array[46372] = [46418, 46419, 46421];
$array[46421] = [146880];
$out = [];
$keys = array_keys($array);
$first_key = reset($keys); // $first_key = 44259
foreach ($array as $k => $items) {
foreach ($items as $val) {
$out[$first_key][] = $val;
}
}
print_r($out);
输出:
Array
(
[44259] => Array
(
[0] => 50007
[1] => 50009
[2] => 46372
[3] => 50008
[4] => 50010
[5] => 46418
[6] => 46419
[7] => 46421
[8] => 146880
)
)
答案 2 :(得分:0)
$res = array();
$res[44259] = array();
foreach($array as $pid)
$res[44259] = array_merge($res[44259], $pid);
print_r($res);
?>
输出继电器
Array
(
[44259] => Array
(
[0] => 50007
[1] => 50009
[2] => 46372
[3] => 50008
[4] => 50010
[5] => 46418
[6] => 46419
[7] => 46421
[8] => 146880
)
)
答案 3 :(得分:0)
这可能就是这样做的一种方式。创建另一个数组并推送新数组中的所有变量。
$result=[];
foreach ($array as $v1) {
foreach ($v1 as $v2) {
array_push($result,$v2);
}
}
答案 4 :(得分:0)
您是否尝试过https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.7?
$mergedArray = [];
foreach ($array as $subArray) {
$mergedArray = array_merge ($mergedArray, $subArray);
}
如果这不起作用,那么您可以使用array_merge在每个子数组元素上运行一个函数,以在添加它之前检查它是否在合并的数组中。
$mergedArray = [];
foreach ($array as $subArray) {
array_map(function($elm) {
if (!in_array($elm, $mergedArray)) {
$mergedArray[] = $elm;
}, $subArray);
}