重置数组的数字键

时间:2016-01-16 14:30:38

标签: php arrays

我有一个像这样的数组

$array = array(
  1 => 'one',
  2 => 'two',
  3 => 'three',
  'row' => 'four',
  'newRow' => 'five',
);

我需要重新索引数字键 - 1,2,3。

  
    

预期产出:

  
$array = array(
  0 => 'one',
  1 => 'two',
  2 => 'three',
  'row' => 'four',
  'newRow' => 'five',
);

我已尝试使用array_values,但字符串键也会被编入索引。

这样做的最佳方式是什么?

感谢。

2 个答案:

答案 0 :(得分:3)

使用array_merge重新索引数组。

代码:

<?php
$array = array(
    1 => 'one',
    2 => 'two',
    3 => 'three',
    'row' => 'four',
    'newRow' => 'five',
);
$reindexed_array = array_merge($array);
var_dump($reindexed_array);

结果:

array(5) {
    [0]=> string(3) "one"
    [1]=> string(3) "two"
    [2]=> string(5) "three"
    ["row"]=> string(4) "four"
    ["newRow"]=> string(4) "five"
}

您可以在此处找到一个工作示例:https://3v4l.org/Om72e。有关array_merge的更多信息:http://php.net/manual/en/function.array-merge.php

答案 1 :(得分:1)

        $array = array(
          1 => 'one',
          2 => 'two',
          3 => 'three',
          'row' => 'four',
          'newRow' => 'five',
        );

        $newArray = [];

        foreach ($array as $key => $value) {
            if (!is_numeric($key)) {
                $newArray[$key] = $value;
            } else {
                $newArray[] = $value;
            }
        }

        var_dump($newArray);
        die();