我正在尝试遍历数组并使用下一个计算每个值。数据就像
[
['rate' => 1000, 'date' => '2017-07-10'],
['rate' => 2000, 'date' => '2017-08-14'],
['rate' => 3000, 'date' => '2017-08-18'],
['rate' => 1000, 'date' => '2017-07-23']
]
我有[编辑,跟随stackoverflow中另一个问题的示例]:
@foreach ($users as $user)
@if ($user->admin_id == $active_user) // filtering users under this admin
@foreach ($userbillings as $userbilling)
@if($userbilling->user_id == $user->id) // filtering users
<?php
$count = count($userbilling->created_at);
$rates[] = $userbilling->rate;
$diff = 0;
for ($i=0; $i < $count; $i++) {
if (isset($rates[$i + 1])) {
$thisValue = $rates[$i];
$nextValue = $rates[$i + 1];
$diff = $nextValue - $thisValue;
}
}
echo $diff;
?>
@endif
@endforeach
@endif
@endforeach
这给了我结果:1000 2000 3000 1000 3000
我想要实现的是从第二项减去第一项,从第三项减去第二项,从第四项减去第三项,依此类推,直至到达最后一项。对于最后一项,我想保留整数。
我知道我需要在这里使用数组和循环,并且在过去的两周内我尝试了不同的方法,但是无法接近。
请建议我如何使它工作,或给我一个指导我应该如何进行。我在这里搜索了很多问题,但找不到任何适合我的问题。如果有,请建议我链接。
答案 0 :(得分:0)
您的问题不明确,但这是一个可能对您有所帮助的示例!
使用array_slice()
&amp; array_sum()
$array = array( "0"=>1,"1"=>1,"2"=>5,"3"=>1,"4"=>1,"7"=>1,"8"=>3,"9"=>1);
$keys = array_keys($array);
$array = array_values($array);
$newArr = array();
foreach ($array as $key=>$val) {
$newArr[] = array_sum(array_slice($array, 0, $key+1));
}
$newArr = array_combine($keys, $newArr);
print '<pre>';
print_r($newArr);
print '</pre>';
参考:
答案 1 :(得分:0)
您可以访问foreach循环中的下一个项目,如下面的代码:
foreach ($items as $key => $item)
{
echo !empty($items[$key+1]) ? ($items[$key+1]->rate - $item->rate) : $itema->rate;
}
答案 2 :(得分:0)
您还没有指定首选输出,但假设您希望最终得到所有对的计算结果,加上最后一个元素,这可以让您走上正确的轨道。 / p>
我还会在上面发表评论 - 不要在视图中执行此类逻辑,因为它属于控制器或某个服务。保持您的观点尽可能简单。
未经测试,请自行完成:
<?php
$periods = [
['rate' => 1000, 'date' => '2017-07-14'],
['rate' => 3000, 'date' => '2017-08-18'],
['rate' => 2000, 'date' => '2017-08-10'],
['rate' => 3000, 'date' => '2017-08-15'],
['rate' => 1000, 'date' => '2017-08-23'],
];
$lastPeriod = count($periods) - 1;
$ratesForPeriods = [];
foreach ($periods as $index => $currentPeriod) {
if ($index === $lastPeriod) {
$ratesForPeriods[] = $currentPeriod; // add the last as-is
} else {
$nextPeriod = $periods[$index + 1];
$currentDate = new DateTime($currentPeriod['date']);
$interval = $currentDate->diff(new DateTime($nextPeriod['date']));
$ratesForPeriods[] = [
'from' => $currentPeriod['date'],
'to' => $nextPeriod['date'],
'rate' => $currentPeriod['rate'],
'days' => $interval->days,
'total' => $interval->days * $currentPeriod['rate'],
];
}
}
print_r($ratesForPeriods);
收率:
Array
(
[0] => Array
(
[from] => 2017-07-14
[to] => 2017-08-18
[rate] => 1000
[days] => 35
[total] => 35000
)
[1] => Array
(
[from] => 2017-08-18
[to] => 2017-08-10
[rate] => 3000
[days] => 8
[total] => 24000
)
[2] => Array
(
[from] => 2017-08-10
[to] => 2017-08-15
[rate] => 2000
[days] => 5
[total] => 10000
)
[3] => Array
(
[from] => 2017-08-15
[to] => 2017-08-23
[rate] => 3000
[days] => 8
[total] => 24000
)
[4] => Array
(
[rate] => 1000
[date] => 2017-08-23
)
)
希望这会有所帮助:)