将键添加到索引数组PHP

时间:2019-01-09 05:31:40

标签: php arrays

我有以下数组

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

我有一个开始时间和一个结束时间,我想要预订结果或提供类似以下数组的结果

Array
    (
        [availiable] => 09:00
        [availiable] => 09:30
        [booked] => 10:00
        [booked] => 10:30
        [availiable] => 11:00
        [availiable] => 11:30
        [availiable] => 12:00
        [availiable] => 12:30
        [availiable] => 12:30
    )

我尝试了以下代码,但没有成功

$array=array("09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30");
    $start = "09:40";
    $end = "10:30";
$tmp = array();
foreach ($array as $arr) {
     if($arr=="09:30") {
             $tmp['booked'] = $arr;
      }
    else
    {
        $tmp['availiable'] = $arr;
    }
}

$ss=array_merge($array,$tmp);   
echo "<pre>";print_R($ss);

2 个答案:

答案 0 :(得分:4)

数组中不能有多个相同的键。但是,您可以使用此代码获得可行的结果。它使用array_map处理$cars数组中的每个元素,以确定时间是否已预定或可用;然后使用array_combine$cars的值用作键来组合结果:

$cars=array("09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30");
$start = "09:40";
$end = "10:30";
$availability = array_combine($cars, array_map(function ($v) use ($start, $end) { 
    return (strtotime($v) < strtotime($start) || strtotime($v) > strtotime($end)) ? 'available' : 'booked'; }, 
    $cars));
print_r($availability);

输出:

Array ( 
    [09:00] => available
    [09:30] => available
    [10:00] => booked
    [10:30] => booked
    [11:00] => available
    [11:30] => available
    [12:00] => available
    [12:30] => available
)

Demo on 3v4l.org

答案 1 :(得分:0)

您正在尝试创建多个相同的键,这是不可能的,因为如果您引用$array['available'],那么应该显示哪个键?未知!

无论如何,我建议创建两个密钥,一个booked和一个available,那样您就可以在其中存储时间。

示例:

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

$start = "09:40";
$end = "10:30";

$times = array();
foreach ($array as $time) {
  if($time=="09:30") {
    $times['booked'][] = $time;
  } else {
    $times['availiable'][] = $time;
  }
}

print_r($times);

结果:

Array
(
    [availiable] => Array
        (
            [0] => 09:00
            [1] => 10:00
            [2] => 10:30
            [3] => 11:00
            [4] => 11:30
            [5] => 12:00
            [6] => 12:30
        )

    [booked] => Array
        (
            [0] => 09:30
        )

)