分解数组,以便每个第二个元素位于不同的数组中

时间:2019-04-21 08:33:57

标签: php arrays

因此,我想采用一个“未排序”数组,并从“未排序”数组中取出第二个元素,然后将其放入新数组,所以剩下的就是两个数组。

$unsorted = array("present","Bob","late","Jessie","late","Carl","present","Jessica","absent","Adam","present","Hope");

我曾考虑创建一个for循环,但是找不到任何函数来创建两个数组。

任何帮助将不胜感激,谢谢!

2 个答案:

答案 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);