Say I have this array
说我有这个数组
$array = array('pen' => 'blue', 'paper' => 'red', 'ink' => 'white');
When I loop through it
当我循环它
$string = '';
foreach ($array AS $key=>$value) {
$string .= $key . ' = ' . $value;
}
I want to get the "line number" of the element the loop is currently on.
我想得到循环当前所在元素的“行号”。
If the loop is on "pen" I would get 1. If the loop is on "paper" I would get 2. If the loop is on "ink" I would get 3.
如果循环是“笔”,我会得到1.如果循环是“纸”我会得到2.如果循环是“墨水”,我会得到3。
Is there an array command for this?
这有一个数组命令吗?
3 个解决方案
#1
6
No. You will have to increment an index counter manually:
不可以。您必须手动递增索引计数器:
$string = '';
$index = 0;
foreach ($array as $key=>$value) {
$string .= ++$index . ") ". $key . ' = ' . $value;
}
#2
2
Use array_values()
function to extract values from array. It indexes array numerically and $key will be the index of value in loop.
使用array_values()函数从数组中提取值。它以数字方式对数组进行索引,$ key将是循环中的值索引。
$array = array('pen' => 'blue', 'paper' => 'red', 'ink' => 'white');
$array = array_values($array);
$string = '';
foreach ($array as $key => $value) {
$string .= $key + 1 . ' = ' . $value;
}
#3
0
$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
}
Hope that helps.
希望有所帮助。
#1
6
No. You will have to increment an index counter manually:
不可以。您必须手动递增索引计数器:
$string = '';
$index = 0;
foreach ($array as $key=>$value) {
$string .= ++$index . ") ". $key . ' = ' . $value;
}
#2
2
Use array_values()
function to extract values from array. It indexes array numerically and $key will be the index of value in loop.
使用array_values()函数从数组中提取值。它以数字方式对数组进行索引,$ key将是循环中的值索引。
$array = array('pen' => 'blue', 'paper' => 'red', 'ink' => 'white');
$array = array_values($array);
$string = '';
foreach ($array as $key => $value) {
$string .= $key + 1 . ' = ' . $value;
}
#3
0
$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
}
Hope that helps.
希望有所帮助。