繁体   English   中英

PHP:在foreach循环中关联数组索引名称

[英]PHP: Associate array index name in a foreach loop

通过执行以下操作,可以从foreach循环中获取索引号。

foreach ($rows as $index=>$row)
{
    echo $index.": ".$row;
    // gives me "1: $row etc 
}

如果我的数组是关联数组,是否可以在循环中获取关联名称而不是索引号?

实际上,您已经做好了:

$associativeArray = array(
    'First'  => 1,
    'Second' => 2,
    'Third'  => 3,
); 
foreach ($associativeArray as $index => $value) {
    echo $index . ": " . $value;
}
    // First:  1
    // Second: 2
    // Third:  3
<?
$rows = array();
$rows['hi'] = 'there';
$rows['foo'] = 'bar';
foreach ($rows as $index=>$row)
{
    echo $index.": ".$row;
    // $index will be hi and foo
}
?>

PHP数组是关联的,其中常规数组只是将整数作为键。

PHP文档实际上在第一句话中提到了这一点: http : //php.net/manual/en/language.types.array.php

An array in PHP is actually an ordered map. PHP没有数组,它具有被称为数组的地图/字典,但它们不是其他语言中的数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM