php - 重复并合并 PHP 数组
问题描述
有了array_fill
,我想重复和合并数组。
例如,当我执行时:
$array = array_fill(0, 2, array_merge(
['hello'],
['by']
));
var_dump($array);
我有这个结果:
array(2) {
[0]=>
array(2) {
[0]=>
string(5) "hello"
[1]=>
string(2) "by"
}
[1]=>
array(2) {
[0]=>
string(5) "hello"
[1]=>
string(2) "by"
}
}
但我想要这个结果:
array(4) {
[0]=>
string(5) "hello"
[1]=>
string(2) "by"
[2]=>
string(5) "hello"
[3]=>
string(2) "by"
}
解决方案
有很多方法可以做到这一点,但这是一个很好的机会来展示如何使用各种 PHP 迭代器来做到这一点,包括ArrayIterator
,InfiniteIterator
和LimitIterator
; 例如:
// create an ArrayIterator with the values you want to cycle
$values = new ArrayIterator(['hello', 'by']);
// wrap it in an InfiniteIterator to cycle over the values
$cycle = new InfiniteIterator($values);
// wrap that in a LimitIterator defining a max of four iterations
$limit = new LimitIterator($cycle,0, 4);
// then you can simply foreach over the values
$array = [];
foreach ($limit as $value) {
$array[] = $value;
}
var_dump($array);
产量:
array(4) {
[0]=>
string(5) "hello"
[1]=>
string(2) "by"
[2]=>
string(5) "hello"
[3]=>
string(2) "by"
}
希望这可以帮助 :)
推荐阅读
- java - 自动装配 @ConfigurationProperties POJO 时出现 NullPointerException
- python - 根据类别的平均值估算 NaN 值
- python - 如何使用 MQTT 获得一次性消息?
- java - 在读取文件和写入新文件期间替换与特定值不同的字符
- sql - Oracle DB - 单次查询非线性时间分组报表(1天1周1个月3个月总计)
- spring - 我如何在春季 mongo 中使用条件运算符更新 MongoDB 文档
- ios - 如何缩小 CPTXYGraph 和 CPTGraphHostingView 之间的差距?
- python - Openpyxl追加不会在行尾添加数据
- python - 检查给定值是否在给定数组中的任何数字之间
- ios - Swift:CollectionView 的 indexPath.row 没有增加