Php 如何获取关联数组的当前元素计数?
假设我有这个数组Php 如何获取关联数组的当前元素计数?,php,arrays,loops,foreach,Php,Arrays,Loops,Foreach,假设我有这个数组 $array = array('pen' => 'blue', 'paper' => 'red', 'ink' => 'white'); 当我循环通过它时 $string = ''; foreach ($array AS $key=>$value) { $string .= $key . ' = ' . $value; } 我想得到循环当前所在元素的行号 如果循环在笔上,我会得到1。 如果循环在纸上,我会得到2。 如果循环在墨水上,我会得到3
$array = array('pen' => 'blue', 'paper' => 'red', 'ink' => 'white');
当我循环通过它时
$string = '';
foreach ($array AS $key=>$value) {
$string .= $key . ' = ' . $value;
}
我想得到循环当前所在元素的行号
如果循环在笔上,我会得到1。
如果循环在纸上,我会得到2。
如果循环在墨水上,我会得到3
是否有用于此的数组命令?否。您必须手动递增索引计数器:
$string = '';
$index = 0;
foreach ($array as $key=>$value) {
$string .= ++$index . ") ". $key . ' = ' . $value;
}
使用函数从数组中提取值。它以数字形式对数组进行索引,$key将是循环中值的索引
$array = array('pen' => 'blue', 'paper' => 'red', 'ink' => 'white');
$array = array_values($array);
$string = '';
foreach ($array as $key => $value) {
$string .= $key + 1 . ' = ' . $value;
}
希望有帮助
$i = 0;
foreach ($array as $key=>$value) { // For each element of the array
print("Current non-associative index: ".$i."<br />\n"); // Output the current index
$i++; // Increment $i by 1
}