重置PHP数组索引

时间:2011-09-24 04:08:27

标签: php arrays

我有一个如下所示的PHP数组:

[3] => Hello
[7] => Moo
[45] => America

PHP的功能是什么?

[0] => Hello
[1] => Moo
[2] => America

3 个答案:

答案 0 :(得分:217)

array_values()函数 [docs] 执行此操作:

$a = array(
    3 => "Hello",
    7 => "Moo",
    45 => "America"
);
$b = array_values($a);
print_r($b);
Array
(
    [0] => Hello
    [1] => Moo
    [2] => America
)

答案 1 :(得分:0)

使用array_keys()函数获取数组的键,并使用array_values()函数获取数组的值。

您要获取数组的值:

$array = array( 3 => "Hello", 7 => "Moo", 45 => "America" );

$arrayValues = array_values($array);// returns all values with indexes
echo '<pre>';
print_r($arrayValues);
echo '</pre>';

输出:

Array
(
    [0] => Hello
    [1] => Moo
    [2] => America
)

您要获取数组的键:

$arrayKeys = array_keys($array);// returns all keys with indexes
    echo '<pre>';
    print_r($arrayKeys);
    echo '</pre>';

输出:

Array
(
    [0] => 3
    [1] => 7
    [2] => 45
)

答案 2 :(得分:0)

如果出于某种原因要重置数组的键计数,则

$array1 = [
  [3]  => 'Hello',
  [7]  => 'Moo',
  [45] => 'America'
];
$array1 = array_merge($array1);
print_r($array1);

输出:

Array(
  [0] => 'Hello',
  [1] => 'Moo',
  [2] => 'America'
)