不连续的数组索引

时间:2014-11-11 04:46:29

标签: php arrays

我的数组中包含不那么连续的索引号,如下所示:

$arr[0] = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' );
$arr[1] = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' );
$arr[3] = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' );
$arr[7] = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' );
$arr[8] = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' );

我希望索引号是连续的,如0,1,2,3,4,但下面的代码不起作用。它只适用于连续的索引号,在这种情况下是0和1,并且只是停在那里。

$idx = 0;
$new_arr = array();

for( $i = 0; $i < sizeof( $arr ); $i++ ) {
    if( isset( $arr[$i] ) ) {
        $new_arr[$idx] = $arr[$i];
        $idx++;
    }
}

任何想法如何让这项工作?

3 个答案:

答案 0 :(得分:3)

只需做$arr = array_values($arr);

即可

答案 1 :(得分:0)

您可以使用

$arr[0] = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' );
$arr[1] = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' );
$arr[3] = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' );
$arr[7] = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' );
$arr[8] = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' );
$new_arr = array();
foreach($arr as $a){
    array_push( $new_arr,$a);
}
echo "<pre>";
print_r($new_arr);
echo "</pre>";exit;

答案 2 :(得分:0)

使用

$array_with_new_keys = array_values($arr); // sorted by original key order

echo "<pre>";print_r($array_with_new_keys);