PHP:如果数组是关联数组,如何通过其数字偏移量获取数组的值


PHP: How to get an array's value by its numeric offset if it's an associative array?

我有一个关联数组,当 var 转储时看起来像这样:

Array
(
    [tumblr] => Array
        (
            [type] => tumblr
            [url] => http://tumblr.com/
        )
    [twitter] => Array
        (
            [type] => twitter
            [url] => https://twitter.com/
        )
)

如您所见,键是自定义的"tumblr"和"twitter",而不是数字 0 和 1。

有时我需要通过自定义键获取值

,有时我需要通过数字键获取值。

有什么方法可以让$myarray[0]输出:

(
    [type] => tumblr
    [url] => http://tumblr.com/
)

您可以通过array_values()运行数组:

$myarray = array_values( $myarray);

现在您的数组如下所示:

array(2) {
  [0]=>
  array(2) {
    ["type"]=>
    string(6) "tumblr"
    ["url"]=>
    string(18) "http://tumblr.com/"
  } ...

这是因为array_values()只会从数组中获取值并将数组重置/重新排序/重新键入为数字数组。

您可以使用array_values获取带有数字索引的数组的副本。