如何计算数组中值的顺序?
我有一个包含几个值的数组,想做这样的事情:
$arrayvalues = array_reverse(explode(', ', somefunction()));
foreach ( $arrayvalues as $arrayvalue ) :
printf('<li class="'.$countvalue.'">'.$arrayvalue.'</li>');
endforeach;
我想在 $countvalue 中包含数组中值的数量,
即......数组将是这样的: ("apple", "orange ", "grapefruit")
我希望数字与这些值的顺序号相匹配 苹果 = 1,橙色 = 2,葡萄柚 = 3
或者实际上即使它只是根据回显的值的增量数字也没关系,我只需要插入一个由
我尝试玩 $i 的增量数字表示的 css 类。 ..算...但我不知道如何实现我想要的;我更像是一名设计师而不是编码员,我查看了 PHP 帮助,但找不到适合我的案例的明确解决方案,
谢谢
I have an array with a few values and want to do something like this:
$arrayvalues = array_reverse(explode(', ', somefunction()));
foreach ( $arrayvalues as $arrayvalue ) :
printf('<li class="'.$countvalue.'">'.$arrayvalue.'</li>');
endforeach;
I want to have in $countvalue the number of the value in the array
ie... the array will be something like this: ("apple", "orange", "grapefruit")
I want the number to match the order number of these values
apple = 1, orange = 2, grapefruit = 3
or actually even if it's just an incremental number according to the values echoed it doesn't matter, I just need to insert a css class represented by an incremembtal number
I tried playing $i... count... but I don't know how to achieve what I want; I'm more a designer than a coder, I looked in the PHP help but couldn't find a clear solution for my case
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您已经有了基于订单的增量编号。请记住,只有当您的密钥是从 0 开始时,这才有效。如果您使用关联数组,则需要使用
for
循环(如 nickb)。You already have an incremental number based on order. Keep in mind, this only works if your key's are 0-based. If you use an associative array you will need to use a
for
loop instead (as suggested by nickb).使用
for
循环迭代数组,如下所示:如果您希望索引
$i
从 1 开始,则需要在 printf 语句中添加 1。旁注:如果您实际上没有生成格式化输出,则此处不需要 printf。
Use a
for
loop to iterate over your array, like so:If you want the index
$i
to start at one, you need to add one in the printf statement.Side note: You don't need printf here if you're not actually generating formatted output.
我们(或我)建议您使用普通的 for 循环。
We (or I) advise you use a normal for loop.