如何获取关联数组的当前元素数?
16lz
2021-01-22
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;
}
更多相关文章
- PHP用空格分割文本为数组的方法
- 如何使用ChromePhp Logger记录数组
- 在数组中计数,其中值为0
- 如何将PHP数组的关联数组转移到javascript?
- PHP - 将字符串转换为键值数组
- 如何在不更改其键值的情况下删除数组的第一个元素?
- 以完整二叉树,数组格式获取所有节点
- php 写一个算法,查寻数组里第一个大于某数的值。
- 插入PHP数组作为MYSQL列