移位数组值PHP

时间:2018-05-09 07:44:13

标签: php arrays

请帮帮我。我有以下数组:

    [0] => Array (
        [0] => Name
        [1] => Age
        )
    [1] => Array (
        [0] => Name 1
        [1] => 20
        )
    [2] => Array (
        [0] => Name 2
        [1] => 21
        )
    [3] => Array (
        [0] => Name 3
        [1] => 22
        )
    [4] => Array (
        [0] => Name 4
        [1] => 23
        )
    [5] => Array (
        [0] => Name 5
        [1] => 24
        )

我想实现像这个输出一样移位数组的值:

因为将excel文件导出到php数据库时,将错误地插入1行年龄的移位:

[0] => Array (
    [0] => Name
    [1] => 20
    )
[1] => Array (
    [0] => Name 1
    [1] => 21
    )
[2] => Array (
    [0] => Name 2
    [1] => 22
    )
[3] => Array (
    [0] => Name 3
    [1] => 23
    )
[4] => Array (
    [0] => Name 4
    [1] => 24
    )
[5] => Array (
    [0] => Name 5
    [1] => 25
    )

提前致谢。

1 个答案:

答案 0 :(得分:0)

您也可以循环然后检查最后一个数组键

$array = [
    ["Name","Age"], ["Name 1","20"], ["Name 2","23"], ["Name 3","30"],
    ["Name 4","20"], ["Name 5","26"], ["Name 6","27"], ["Name 7","21"], ["Name 8","26"]
    ];

// Get last array key using count() or you can use end() then key()
$last_key = count($array) - 1; 

$result = []; // initialize result array

foreach ($array as $key => $value) {
    if ($key == $last_key) break;                       // if last key, break loop
    $result[] = [ $array[$key][0], $array[++$key][1] ]; // push name, age+1 values
}

print_r($result);