如何使用PHP从时间数组中减去时间?
大家好,我有一个与某些PHP脚本有关的问题。
我有一个包含时间=&gt的数组; ['12:10','4:16','2:5'],并具有一个HTML形式,其中包含类型'数字'的输入字段。
我想要在表单输入字段中输入一些值时,例如输入7,因此在后端提交表单后,我在输入字段中输入的数字7将从上面提到的数组中减去,我将获得结果数组喜欢: ['5:10','4:16','2:5']
我已经尝试过这样的事情,但无法实施我的逻辑
$val = array(1, 0, 2, 1, 1);
$subtract = 3.5;
foreach ($val as $key => $item) {
if ($subtract >= $item) {
$subtract -= $item;
$val[$key] = 0;
} else {
$val[$key] -= $subtract;
$subtract = 0;
}
}
任何帮助
Hello seniors I have a question related to some PHP script.
I have an array containing time => ['12:10', '4:16', '2:5'] and have one html form containing input field of type 'number'.
I want when I enter some value in my form input field for example I enter 7, so after submitting the form in back-end the number 7 which i enter in input field is subtracted from the array which I mentioned above and I will get the result array like:
['5:10', '4:16', '2:5']
I have tried something like that but not able to implement my logic
$val = array(1, 0, 2, 1, 1);
$subtract = 3.5;
foreach ($val as $key => $item) {
if ($subtract >= $item) {
$subtract -= $item;
$val[$key] = 0;
} else {
$val[$key] -= $subtract;
$subtract = 0;
}
}
Any kind of help is highly appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用碳库进行日期/时间操作:
You can use Carbon library for date/time manipulation:
Test Carbon library online
无需库,只需将您的第一个数组转换为秒:1小时= 3600; 1分钟= 60; 12:10是12 x 3600 + 10 x 60,然后您对$ _post值进行相同的操作,然后使用 gmdate()要检索数组的原始格式
No need for library, just convert your first array to seconds: 1 hour = 3600 ; 1 minute = 60 ; 12:10 is 12 x 3600 + 10 x 60, then you do the same thing to your $_POST value, then use gmdate() to retrieve the original format of your array
您的示例有点模棱两可。您是否只想总是从数组的第一个元素中减去字段值?还是仅来自那些大于提交价值的要素?
从MM:SS Time String中减去分钟很简单。最简单的可能是概括,以便允许减去金额为
mm:ss
,而不是始终是整数分钟。我只会爆炸它们两个,将它们总共变成秒(分钟*60+秒),减去这些,然后转回MM:SS。两种转换都可能值得自己的功能:然后减法很容易:
如果您想从每个足够大的元素中减去,则可以使用这样的循环:
比较有效第一个非数字,因此'12:10'只是12,即> 7。
Your example is a little ambiguous. Do you only want to subtract the field value from the first element of the array, always? Or only from those elements which are greater than the submitted value?
It's pretty straightforward to subtract minutes from a mm:ss time string; simplest is probably to generalize so that the amount to subtract is also allowed to be
mm:ss
instead of always being a whole number of minutes. I would just explode both of them, turn them into total seconds (minutes*60+seconds), subtract those, and then turn back into mm:ss. Both conversions might be worth their own functions:And then the subtraction is easy:
If you want to subtract from each element that is big enough, you could use a loop like this:
The comparison works because the cast from string to int ignores everything after the first non-digit, so '12:10' just becomes 12, which is > 7.