Built-in PHP function to reset the indexes of an array?

前端 未结 4 904
悲哀的现实
悲哀的现实 2021-01-13 04:50

Example:

$arr = array(1 => \'Foo\', 5 => \'Bar\', 6 => \'Foobar\');
/*... do some function so $arr now equals:
    array(0 => \'Foo\', 1 => \'         


        
4条回答
  •  没有蜡笔的小新
    2021-01-13 05:06

    To add to the other answers, array_values() will not preserve string keys. If your array has a mix of string keys and numeric keys (which is probably an indication of bad design, but may happen nonetheless), you can use a function like:

    function reset_numeric_keys($array = array(), $recurse = false) {
        $returnArray = array();
        foreach($array as $key => $value) {
            if($recurse && is_array($value)) {
                $value = reset_numeric_keys($value, true);
            }
            if(gettype($key) == 'integer') {
                $returnArray[] = $value;
            } else {
                $returnArray[$key] = $value;
            }
        }
    
        return $returnArray;
    }
    

提交回复
热议问题