fou循环 php 剩余次数_php-计算foreach循环中的迭代次数

php-计算foreach循环中的迭代次数

如何计算一个foreach中有多少个项目?

我要计算总行数。

foreach ($Contents as $item) {

$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15

}

谢谢。

yuli chika asked 2019-11-08T11:59:32Z

10个解决方案

109 votes

首先,如果您只想找出数组中的元素数量,请使用count。现在,回答您的问题...

如何计算一个foreach中有多少个项目?

$i = 0;

foreach ($Contents as $item) {

$i++;

$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15

}

您也可以在这里查看答案:

如何找到foreach索引

aioobe answered 2019-11-08T12:00:07Z

43 votes

您无需在count($Contents)中进行操作。

只需使用count($Contents)。

tjm answered 2019-11-08T12:00:38Z

17 votes

count($Contents);

要么

sizeof($Contents);

gpresland answered 2019-11-08T12:01:00Z

16 votes

foreach ($Contents as $index=>$item) {

$item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15

}

Alejandro Moreno answered 2019-11-08T12:01:17Z

4 votes

您可以通过几种不同的方法来解决这一问题。

您可以在foreach()之前设置一个计数器,然后进行迭代是最简单的方法。

$counter = 0;

foreach ($Contents as $item) {

$counter++;

$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15

}

JimP answered 2019-11-08T12:01:51Z

1 votes

$Contents = array(

array('number'=>1),

array('number'=>2),

array('number'=>4),

array('number'=>4),

array('number'=>4),

array('number'=>5)

);

$counts = array();

foreach ($Contents as $item) {

if (!isset($counts[$item['number']])) {

$counts[$item['number']] = 0;

}

$counts[$item['number']]++;

}

echo $counts[4]; // output 3

webbiedave answered 2019-11-08T12:02:09Z

1 votes

foreach ($array as $value)

{

if(!isset($counter))

{

$counter = 0;

}

$counter++;

}

//对不起,如果代码显示不正确。 :P

//我更喜欢这个版本,因为计数器变量在foreach中,而不是上面。

statistnr1 answered 2019-11-08T12:02:43Z

1 votes

尝试:

$counter = 0;

foreach ($Contents as $item) {

something

your code ...

$counter++;

}

$total_count=$counter-1;

vivekpvk answered 2019-11-08T12:03:03Z

1 votes

您可以执行sizeof($Contents)或count($Contents)

还有这个

$count = 0;

foreach($Contents as $items) {

$count++;

$items[number];

}

Journey Dagoc answered 2019-11-08T12:03:34Z

0 votes

想象一个初始值为$counter = 0;的计数器。

对于每个循环,使用$counter = 0;将计数器值增加1

循环返回的最终计数器值将为for循环的迭代次数。 查找下面的代码:

$counter = 0;

foreach ($Contents as $item) {

$counter++;

$item[number];// if there are 15 $item[number] in this foreach, I want get the value `: 15`

}

试试看

Victor Langat answered 2019-11-08T12:04:22Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值