我有一个数组,如:
$list = array('a', 'b', 'c', 'd', 'e',
'f', '1', '2', '3', '4',
'5', '6', '7', '8', '9');
我想分割这个数组,然后将新数组中的每两个项添加为一个组,例如:
$new_list = array(
array('a', 'b'),
array('c', 'd'),
array('e', 'f'),
array('1', '2'),
array('3', '4'),
array('5', '6'),
array('7', '8'),
array('9'), // note that this one here is alone!
);
但我想用foreach
或其他东西来做这件事。我只知道我可以用 2 来划分我的数组的长度,并使用round
或floor
PHP函数来获取整数,但我无法弄清楚如何分组每个数组有两个项目的数组项。
请帮助我,我的大脑溢出......
答案 0 :(得分:2)
$list = ['a', 'b', 'c', 'd', 'e',
'f', '1', '2', '3', '4',
'5', '6', '7', '8', '9'];
$list2 = [];
$c = 0;
$temp_array = [];
for ($i = 0; $i < Count($list); $i++)
{
$c++;
array_push($temp_array, $list[$i]);
if ($c >= 2)
{
array_push($list2, $temp_array);
$temp_array = [];
$c = 0;
}
}
print_r($list2);
echo '<br />List2: ' . count($list2) . '<br />List: ' . count($list);
编辑:或Mark Baker提供array_chunk()功能的解决方案。它的代码较少。