php 合并多个数组中的数字

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 合并多个数组中的数字相关的知识,希望对你有一定的参考价值。

<?php
//------------------------------------
// Functions
function flatternArray($targetArray){
	$flatArray = [];
	foreach($targetArray as $array) {
		if (is_array($array)) {
			$flatArray = array_merge($flatArray, flatternArray($array));
		} else {
			$flatArray[] = $array;
		}
	}
	
	return $flatArray;
}
$eol = PHP_EOL;


$t1 = [1,2,3];
$t2 = [2,3,4];
$t3 = [9,8];

$position = 0;
$items = [$t1, $t2, $t3];
$output = [];
$working = [];
echo "Items Count: ".count($items).$eol;
do{
    echo "Position: ".$position.$eol;
    $working = $items[$position];
    
    // TODO: To stupid, need rework
    $tmp_items = $items;
    unset($tmp_items[$position]);
    $tmp_array = flatternArray($tmp_items);
    
    foreach($working as $prefix){
        foreach($tmp_array as $subfix){
            $target = $prefix.$subfix;
            $output[] = $target;
        }
    }
    $position++;
    $working = [];
}while($position < count($items));

print_r($output);

/*
Sample Output:

Items Count: 3
Position: 0
Position: 1
Position: 2
Array
(
    [0] => 12
    [1] => 13
    [2] => 14
    [3] => 19
    [4] => 18
    [5] => 22
    [6] => 23
    [7] => 24
    [8] => 29
    [9] => 28
    [10] => 32
    [11] => 33
    [12] => 34
    [13] => 39
    [14] => 38
    [15] => 21
    [16] => 22
    [17] => 23
    [18] => 29
    [19] => 28
    [20] => 31
    [21] => 32
    [22] => 33
    [23] => 39
    [24] => 38
    [25] => 41
    [26] => 42
    [27] => 43
    [28] => 49
    [29] => 48
    [30] => 91
    [31] => 92
    [32] => 93
    [33] => 92
    [34] => 93
    [35] => 94
    [36] => 81
    [37] => 82
    [38] => 83
    [39] => 82
    [40] => 83
    [41] => 84
)


*/

以上是关于php 合并多个数组中的数字的主要内容,如果未能解决你的问题,请参考以下文章

php 函数合并 array_merge 与 + 的区别

PHP合并数组的三种方法的分析与比较

【php】合并多个数组并去掉相同的

array_merge — 合并一个或多个数组

array_merge — 合并一个或多个数组

php--------合并2个数字键数组的值