作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我试图从两组数组中平均划分数组
例如:
$arr1 = [a,b,c,d,e];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];
我尝试过的:
$arr1 = [a,b,c,d,e];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];
$arrRes = [];
$key = 0;
for($i=0;$i<count($arr1);$i++){
$arrRes[$arr1[$key]][] = $arr2[$i];
$key++;
}
$key2 = 0;
for($k=0;$k<count($arr1);$k++){
$arrRes[$arr1[$key2]][] = $arr2[$key];
$key++;
$key2++;
if ($key == count($arr2)) {
break;
}
}
我希望得到输出:
[
"a" => [1,6,11],
"b" => [2,7,12],
"c" => [3,8,13],
"d" => [4,9],
"e" => [5,10]
]
但我得到的实际输出是:
[
"a" => [1,6],
"b" => [2,7],
"c" => [3,8],
"d" => [4,9],
"e" => [5,10]
]
最佳答案
另一种只使用一个循环的方法(代码中的注释)...
$arr1 = ['a','b','c','d','e'];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];
// Create output array from the keys in $arr1 and an empty array
$arrRes = array_fill_keys($arr1, []);
$outElements = count($arr1);
// Loop over numbers
foreach ( $arr2 as $item => $value ) {
// Add the value to the index based on the current
// index and the corresponding array in $arr1.
// Using $item%$outElements rolls the index over
$arrRes[$arr1[$item%$outElements]][] = $value;
}
print_r($arrRes);
输出...
Array
(
[a] => Array
(
[0] => 1
[1] => 6
[2] => 11
)
[b] => Array
(
[0] => 2
[1] => 7
[2] => 12
)
[c] => Array
(
[0] => 3
[1] => 8
[2] => 13
)
[d] => Array
(
[0] => 4
[1] => 9
)
[e] => Array
(
[0] => 5
[1] => 10
)
)
关于php - 如何在 PHP 中平均划分两个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55598880/
我是一名优秀的程序员,十分优秀!