因此,我想采用一个“未排序”数组,并从“未排序”数组中取出第二个元素,然后将其放入新数组,所以剩下的就是两个数组。
$unsorted = array("present","Bob","late","Jessie","late","Carl","present","Jessica","absent","Adam","present","Hope");
我曾考虑创建一个for
循环,但是找不到任何函数来创建两个数组。
任何帮助将不胜感激,谢谢!
答案 0 :(得分:1)
一种选择是使用经典的foreach
循环。
$unsorted = array("present","Bob","late","Jessie","late","Carl","present","Jessica","absent","Adam","present","Hope");
$array1 = array();
$array2 = array();
foreach( $unsorted as $key => $val ) {
if ( $key % 2 ) $array2[] = $val;
else $array1[] = $val;
}
$array1
将导致:
Array
(
[0] => present
[1] => late
[2] => late
[3] => present
[4] => absent
[5] => present
)
$array2
将导致:
Array
(
[0] => Bob
[1] => Jessie
[2] => Carl
[3] => Jessica
[4] => Adam
[5] => Hope
)
答案 1 :(得分:0)
简单,但需要一些理解:
$unsorted = array("present","Bob","late","Jessie","late","Carl","present","Jessica","absent","Adam","present","Hope");
$sorted = array_map(null, ...array_chunk($unsorted, 2));
print_r($sorted);