我们不能在键值为 PHP 的数组上使用数字索引吗?
Can't we use numeric index on arrays with key value in PHP?
我在 PHP 中使用如下键值对定义了一个数组:
$myArray = (
'item1' => 'val1',
'item2' => 'val2',
'item3' => 'val3'
);
但是每当我需要使用像 $myArray[1]
这样的数字索引来使用此数组中的存储值之一时,我会收到以下错误消息:
Notice: Undefined offset: 1 ...
以前我虽然在定义数组成员时总是创建数字索引,但现在这个错误告诉我我错了。
我的问题是:我们不能对使用 PHP 中的键值对创建的数组使用数字索引吗?
不,您不能通过数字索引访问关联数组的值。但是你可以先通过 array_values
传递你的数组来得到你想要的:
echo array_values($myArray)[1];
array_values() returns all the values from the array and indexes the array numerically.
您可以在明确需要时使用 array_keys:
$arrayKeys = array_keys($myArray);
echo $myArray[$arrayKeys[0]];
或者在 foreach 中:
foreach($myArray as $key=>$value) {
//$ key stores item1,item2,item3
//$value stores $val1, val2,val3
}
我在 PHP 中使用如下键值对定义了一个数组:
$myArray = (
'item1' => 'val1',
'item2' => 'val2',
'item3' => 'val3'
);
但是每当我需要使用像 $myArray[1]
这样的数字索引来使用此数组中的存储值之一时,我会收到以下错误消息:
Notice: Undefined offset: 1 ...
以前我虽然在定义数组成员时总是创建数字索引,但现在这个错误告诉我我错了。
我的问题是:我们不能对使用 PHP 中的键值对创建的数组使用数字索引吗?
不,您不能通过数字索引访问关联数组的值。但是你可以先通过 array_values
传递你的数组来得到你想要的:
echo array_values($myArray)[1];
array_values() returns all the values from the array and indexes the array numerically.
您可以在明确需要时使用 array_keys:
$arrayKeys = array_keys($myArray);
echo $myArray[$arrayKeys[0]];
或者在 foreach 中:
foreach($myArray as $key=>$value) {
//$ key stores item1,item2,item3
//$value stores $val1, val2,val3
}