根据时间PHP从数组中删除值

时间:2019-01-08 05:00:57

标签: php arrays

我想从数组累加中删除一些值,例如,我想删除9:30到10:30之间的值(时间段将动态变化),这是我的代码

{
    "name": "lc-portal",
    "version": "1.0.0",
    "description": "MY APP",
    "main": "server/start.js",
    "scripts": {
        "start": "nodemon --watch server -e js,html server/start.js",
        "postinstall": "gulp build"
    },
    "engines": {
        "node": "your_node_version"
    }
}

现在,我想要像这样的数组(因为预订了9:30到10:30之间的时间)

<select [(ngModel)] = "bindingobject.studentId" name= " studentName">

<Option selected = true > Select <option>

<Option *ngFor = " let Stu of StudentEntity " value  = " {{Stu.studentId}} > {{Stu.studentName}}</option>
</Select>

我尝试了以下代码,但只删除了开始时间,我该怎么办?

$cars=array("09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30");

4 个答案:

答案 0 :(得分:1)

假设您在$start$end中有开始和结束时间,则可以使用array_filter删除预订时间,如下所示:

    $cars=array("09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30");
$start = "09:30";
$end = "10:30";
$cars = array_filter($cars, function ($v) use ($start, $end) { 
    return strtotime($v) < strtotime($start) || strtotime($v) > strtotime($end); });
print_r($cars);

输出:

Array ( [0] => 09:00 [4] => 11:00 [5] => 11:30 [6] => 12:00 [7] => 12:30 )

Demo on 3v4l.org

答案 1 :(得分:1)

尽管我喜欢Nick的方法,但是您可以使用的另一种方法是使用foreach循环并将时间作为整数处理...有些人觉得这更易于阅读。

$start = 930; // same as '09:30'
$end   = 1030; // same as '10:30'
$cars  = array('09:00','09:30','10:00','10:30','11:00','11:30','12:00','12:30');

foreach ($cars as $key => $time){
  $time = (int)str_replace(':','',$time);

  // Remove if between the two times...
  if ($time >= $start AND $time <= $end) unset($cars[$key]);
}

var_dump($cars);

应返回:“ 09:00”,“ 11:00”,“ 11:30”,“ 12:00”,“ 12:30”

答案 2 :(得分:0)

您也可以尝试以下一项。

将您的时间转换为strtotime并进行比较,然后再次以人类可读的格式进行转换。

$cars=array("09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30");

$dynamicStartTime="09:30";
$dynamicEndTime="10:30";
$a= strtotime($dynamicStartTime);
$b= strtotime($dynamicEndTime);
$newarray=array();
foreach($cars as $key=>$value){
    $c=strtotime($value);
    if($c>=$a && $c<=$b){
      //inbetween result
    }else{
        $newarray[]=date("H:i", $c);
    }
}
echo "<pre>";
print_r($newarray);

答案 3 :(得分:0)

因为数组已经排序,

$cars=array("09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30");
for($i=0;$i<count($cars);$i++){
    if($cars[$i]=="09:30"){
        unset($cars[$i+1]);
        break;
    }
}
print_r($cars);