我有这样的数组:
[
[
'minutes': 60
]
[
'minutes': 600
],
[
'minutes': 1440
]
]
从响应获取像720
我需要使用我的数组拆分720 例如:
[
'600' => 1,
'60' => 2,
]
所以60 * 2 + 600 = 720
已更新,但$ _rate / 10不正确。也许我不需要在计算中使用%
public function calculate($_rate, $minutes, $results)
{
if(empty($results))
{
dump(['rate' => $_rate, 'minutes' => $minutes, 'remainder' => $minutes % $_rate]);
if(($minutes % $_rate) == 0)
return ['rate' => $_rate, 'count' => $minutes / $_rate];
elseif(($minutes % $_rate) != 0) {
return [
$this->calculate($_rate/10, ($minutes % $_rate), $results),
[
'rate' => $minutes - ($minutes % $_rate), 'count' => $minutes / $minutes - ($minutes % $_rate)
]
];
}
}
}
答案 0 :(得分:0)
使用与此代码中不同的循环:
$array = [
[
'minutes'=> 60
],
[
'minutes'=> 600
],
[
'minutes'=> 1440
]
];
$response = 720;
$remain = $response;
$result = [];
while ($remain > 0) {
for ($i = count($array)-1; $i>=0; $i--) {
$result["{$array[$i]['minutes']}"] = 0;
while ($remain >= $array[$i]['minutes']) {
$result["{$array[$i]['minutes']}"]++;
$remain -= $array[$i]['minutes'];
}
}
}
答案 1 :(得分:0)
使用foreach循环并首先比较最大值 如果$ n大于分钟值,则减去 使用array_count_values可以获得所需的600和60分钟。
$arr =array_reverse($arr);
$n =720;
$res=array();
Foreach($arr as $val){
While($n >= $val['minutes']){
$res[] = $val['minutes'];
$n -= $val['minutes'];
}
If($n == 0) break;
}
$res =array_count_values($res);
$res[$n] = 1; // optional if you want to capture remaining after loop.
Var_dump($res);
https://3v4l.org/1mlIX
或者如果你想捕获剩余的:
https://3v4l.org/6Y7CC
输出
array(2) {
[600] => 1
[60] => 2
}