我正在使用输出数组的foreach
循环
$dinnerDetails = array();
$lastDinnerDate = '';
$newDate = '';
foreach ($invitations as $invitation) {
$lastDinnerDate = $invitation['dinner_date'];
if ($invitation['dinner_date'] > $lastDinnerDate) {
$newDate = 'yes';
} else {
$newDate = 'no';
}
$dinnerDetails[] = array(
'request_id' => $invitation['request_id'],
'dinner_date' => $invitation['dinner_date'],
'dinner_id' => $invitation['dinner_id'],
'new_dinner' => $newDate
);
}
输出看起来像这样
array:4 [▼
0 => array:3 [▼
"request_id" => "48"
"dinner_id" => "36"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "yes"
]
1 => array:3 [▼
"request_id" => "51"
"dinner_id" => "40"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "no"
]
2 => array:3 [▼
"request_id" => "50"
"dinner_id" => "36"
"dinner_date" => "2016-05-27T10:00:00"
"new_date" => "yes"
]
3 => array:3 [▼
"request_id" => "52"
"dinner_id" => "41"
"dinner_date" => "2016-05-27T10:00:00"
"new_date" => "no"
]
]
我的问题是如何计算dinner_id
出现的次数。我想将该值作为数组的一部分传递,因为$dinnerDetails
被传递给视图,因此它可以更容易地显示计数。该视图已经通过foreach
循环显示数据,它只是每个dinner_id
所需的计数
答案 0 :(得分:1)
我假设你想要计算ID而不是标签/名称本身,一个如此简单的方法就是这样做,只需将它放在foreach
循环
$countDinner[$invitation['dinner_id']] = isset($countDinner[$invitation['dinner_id']]) ? $countDinner[$invitation['dinner_id']] + 1 : 1;
一个coud也使用if子句而不是三元运算符如果一个人受到伤害,不要忘记放置
$countDinner = array();
在初始化数组的foreach
循环之前,您现在应该有一个数组,其中包含每个dinner_id
的计数。
要将其添加到现有数组,只需按以下方式循环:
foreach($dinnerDetails as &$dinnerDetail){
$dinnerDetail['count'] = $countDinner[$dinnerDetail['dinner_id']];
}
,最终结果将如下所示
0 => array:3 [▼
"request_id" => "48"
"dinner_id" => "36"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "yes"
"count" => 2
]