代码之家  ›  专栏  ›  技术社区  ›  ghost_of_the_code

用空字符串替换平面数组的重复值

  •  1
  • ghost_of_the_code  · 技术社区  · 1 年前

    我正在填充来自两个来源的日期数组:一个日期数组和两个日期之间的日期范围。

    $dateann = ['2024-08-16', '2024-08-11', '2024-08-16', '2024-09-16'];
    $period = CarbonPeriod::between('2024-08-01', '2024-08-31');
    foreach ($period as $date) {
        $days[] = $date->format('Y-m-d');
    }
    $array_dates = array_merge($dateann, $days);
    

    这可能会导致合并数组中的日期重复。我想用空字符串替换任何重复日期。

    电流输出:

    array: [
      0 => "2024-08-16"
      1 => "2024-08-11"
      2 => "2024-08-16"
      3 => "2024-09-05"
      4 => "2024-08-01"
      5 => "2024-08-02"
      6 => "2024-08-03"
      7 => "2024-08-04"
      8 => "2024-08-05"
      9 => "2024-08-06"
      10 => "2024-08-07"
      11 => "2024-08-08"
      12 => "2024-08-09"
      13 => "2024-08-10"
      14 => "2024-08-11"
      15 => "2024-08-12"
      16 => "2024-08-13"
      17 => "2024-08-14"
      18 => "2024-08-15"
      19 => "2024-08-16"
      20 => "2024-08-17"
      21 => "2024-08-18"
      22 => "2024-08-19"
      23 => "2024-08-20"
      24 => "2024-08-21"
    ]
    

    期望输出:

    array: [
        0 => "2024-08-16"
        1 => "2024-08-11"
        2 => ""
        3 => "2024-09-05"
        4 => "2024-08-01"
        5 => "2024-08-02"
        6 => "2024-08-03"
        7 => "2024-08-04"
        8 => "2024-08-05"
        9 => "2024-08-06"
        10 => "2024-08-07"
        11 => "2024-08-08"
        12 => "2024-08-09"
        13 => "2024-08-10"
        14 => ""
        15 => "2024-08-12"
        16 => "2024-08-13"
        17 => "2024-08-14"
        18 => "2024-08-15"
        19 => ""
        20 => "2024-08-17"
        21 => "2024-08-18"
        22 => "2024-08-19"
        23 => "2024-08-20"
        24 => "2024-08-21"
    ]
    
    2 回复  |  直到 1 年前
        1
  •  2
  •   Barmar    1 年前

    检查当前索引是否与值的第一个索引相同。如果没有,请用空字符串替换该值。

    foreach ($array_dates as $index => $value) {
        if (array_search($value, $array_dates) != $index) {
            $array_dates[$index] = '';
        }
    }
    
        2
  •  0
  •   mickmackusa Tom Green    1 年前

    作为性能比较,使用 array_search() 呼叫的效率将低于基于关键字的搜索。下面演示了如何跳过合并步骤,并在查找数组上使用空合并技术,该数组的大小只会随着遇到唯一日期而增长。

    代码:( PHPize Demo )

    $dateann = ['2024-08-16', '2024-08-11', '2024-08-16', '2024-09-16'];
    foreach ($dateann as &$date) {
        $date = $lookup[$date] ?? $date;  // if not in the lookup, it's new
        $lookup[$date] ??= '';  // flag the date in the lookup to only return an empty string
    }
    $period = CarbonPeriod::between('2024-08-01', '2024-08-31');
    foreach ($period as $obj) {
        $ymd = $obj->format('Y-m-d');
        $dateann[] = $lookup[$ymd] ?? $ymd;  // if not in the lookup, it's new
        $lookup[$ymd] ??= '';  // flag the date in the lookup to only return an empty string
    }
    var_export($dateann);
    
    推荐文章