PHP实现数组元素按对应指定次数重复输出的问题求解
PHP实现数组元素按对应次数重复的解决方案
需求说明
现有两个数组:$IDs存储需要重复的元素,$number_of_seasons存储对应索引元素的重复次数,需生成新数组,让每个$IDs元素按对应位置的$number_of_seasons值重复出现。
原始数组
$IDs数组
$IDs = [ 86456, 83981, 3444, 2296, 21515, 66707, 20507, 66985, 78067, 10364 ];
$number_of_seasons数组
$number_of_seasons = [ 1, 1, 1, 1, 1, 3, // 对应ID 66707重复3次 3, // 对应ID 20507重复3次 1, 1, 1 ];
期望输出
$id3 = [ 86456, 83981, 3444, 2296, 21515, 66707, 66707, 66707, 20507, 20507, 20507, 66985, 78067, 10364 ];
错误代码分析
你尝试的嵌套循环逻辑错误:
$id3 = array (); foreach ($number_of_seasons as $number_of_seasons1){ foreach ($IDs as $id2) { $id3 = array_merge($id3, array_fill (0, $number_of_seasons1, $id2)); } }
这段代码会遍历每个季数,然后完整遍历一遍$IDs数组,把每个ID重复当前季数的次数,导致整个$IDs数组被重复多次,完全不符合"对应索引元素重复"的需求。
正确实现方法
方法一:索引遍历法(直观易懂)
通过遍历数组索引,确保每个ID匹配对应位置的重复次数:
$id3 = []; foreach ($IDs as $index => $id) { // 获取当前ID对应的重复次数,兜底默认1次避免索引异常 $repeatTimes = $number_of_seasons[$index] ?? 1; // 生成重复的ID数组并合并到结果 $id3 = array_merge($id3, array_fill(0, $repeatTimes, $id)); } // 输出结果 print "<pre>"; print_r($id3); print "</pre>";
方法二:array_reduce简化写法
用数组归并函数实现更简洁的逻辑:
$id3 = array_reduce(array_keys($IDs), function($result, $index) use ($IDs, $number_of_seasons) { $repeatTimes = $number_of_seasons[$index] ?? 1; return array_merge($result, array_fill(0, $repeatTimes, $IDs[$index])); }, []); // 输出结果 print "<pre>"; print_r($id3); print "</pre>";
方法三:for循环实现
如果两个数组长度确定一致,也可以用for循环:
$id3 = []; $length = count($IDs); for ($i = 0; $i < $length; $i++) { $repeatTimes = $number_of_seasons[$i] ?? 1; for ($j = 0; $j < $repeatTimes; $j++) { $id3[] = $IDs[$i]; } } // 输出结果 print "<pre>"; print_r($id3); print "</pre>";
内容的提问来源于stack exchange,提问作者David Chriss
相关产品推荐
相关产品推荐

