在foreach循环PHP中汇总记录

时间:2019-06-29 06:59:44

标签: php

我正在使用php laravel,让我们假设$records下面是一个数组,只有3条记录,foreach循环将运行3次。

foreach ($records as $record) {
// Here im using query to get logs against each record id.
$logs = "SELECT delivery, COUNT(*) as logs FROM logs where id = 
$record['id] group by delivery"; 

// Run query and it returns array
var_dump($logs)


}

此转储查询获取这样的记录。

第一次

array (size=2)
  0 => 
    array (size=2)
      'delivery' => string '0' (length=1)
      'logs' => string '1' (length=1)
  1 => 
    array (size=2)
      'delivery' => string '1' (length=1)
      'logs' => string '1' (length=1)

第二次

array (size=1)
  0 => 
    array (size=2)
      'delivery' => string '1' (length=1)
      'logs' => string '1' (length=1)

第三次

array (size=2)
  0 => 
    array (size=2)
      'delivery' => string '0' (length=1)
      'logs' => string '1' (length=1)

  1 => 
    array (size=2)
      'delivery' => string '1' (length=1)
      'logs' => string '1' (length=1)

我想计算类似记录

  • 短信总数; //在上面的示例中,总数为5
  • 总交付量; //在上面的示例中,“已交付”为3
  • 失败总数://在上面的示例中,失败为2

这是我的计算方式 如果delivery = 0,则表示失败;如果delivery = 1,则表示已交付;因此,在上述情况下,有3个交付,2个失败。

这是我尝试过的方法,但没有给我正确的结果。

$logsSENT = $logsFailed = 0;
                    foreach ($logs as $log) {
                        if($log['delivery'] == 1) {
                            $logsSENT +=  $log['logs'] * $smsConsumedPerMessage;
                        }

                        if($log['delivery'] == 0) {
                            $logsFailed +=  $log['logs'] * $smsConsumedPerMessage;
                        }
                    }

$total_sms += $logsSENT + $logsFailed;

BTW 'logs' => string '1' (length=1)的日志值可以大于1,可以为2、3等。

第二,例如,在我的IF中,我将其乘以1 $logsSENT = $logs[1]['logs'] * 1; 1仅用于上述示例,以后可以更改为2、3等

1 个答案:

答案 0 :(得分:-1)

<?php
$array = array(
    array(
        array("delivery" => 0, "logs" => 1),
        array("delivery" => 1, "logs" => 1)
    ),
    array(
        array("delivery" => 1, "logs" => 1)
    ),
    array(
        array("delivery" => 0, "logs" => 1),
        array("delivery" => 1, "logs" => 1)
    )
);

$sum = $deliver = $failed = 0;
foreach ($array as $value) {

    $i=$j=1;
    foreach ($value as $va) {
        if($va['delivery']) {
            $deliver = $deliver + $i;
            $i++;
        } else {
            $failed = $failed + $j;
            $j++;
        }
    }
}
echo 'Total:' .($deliver + $failed).'<br>';
echo 'Deliver: '.$deliver.'<br>';
echo 'Failed: '.$failed.'<br>';

?>