php 用户可用性总和(分钟)

zd287kbt  于 2023-01-12  发布在  PHP
关注(0)|答案(1)|浏览(107)

我想计算用户的总可用性:我是这样存储可用性的:
我有可用性的历史记录,因为用户可以更改他们的可用性,所以我需要用这个求和。
注册日期为第一个更新日期,在更新日期[i]之后为更新日期[i+1],最后更新日期[i+n]为现在;
并获得每个持续时间(分钟):
结束时间-开始时间
我得到的json是这样的:可用性对象为每周

{
  "2022-12-20" (date when user have signup ): [
         {
        dayNumber : 2,
        startHours:08:00,
        endHours :10:00;
        },
        {
        dayNumber : 3,
        startHours:11:00,
        endHours :16:00;
        }
    ],
        "2022-12-28" (date when user have update his availibilties): [
         {
        dayNumber : 2,
        startHours:08:00,
        endHours :10:00;
        },
        {
        dayNumber : 3,
        startHours:11:00,
        endHours :16:00;
        }
    ],
       "2023-01-01"  (date when user have update his availibilties): [
        {
        dayNumber : 5,
        startHours:05:00,
        endHours :10:00;
        },
        {
        dayNumber : 7,
        startHours:19:00,
        endHours :22:00;
        }
    ]
    
    }

我现在要做的是:
我已计算从注册日期到现在的周数:

$number_of_week = Carbon::parse($user->signupDate)->diffInWeeks(Carbon::now());

最后,我想得到用户的总体可用性
谢谢

ztigrdn8

ztigrdn81#

经过我们的交谈,我想我已经了解了问题的全貌,所以让我们看看是否可以一起解决这个问题:
我不确定json从何而来,所以我们先把它赋给一个变量:

$jsonString = '
{
  "2022 - 12 - 20": [
    {
      "dayNumber": 2,
      "startHours": "08:00",
      "endHours": "10:00"
    },
    {
      "dayNumber": 3,
      "startHours": "11:00",
      "endHours": "16:00"
    }
  ],
  "2022 - 12 - 28": [
    {
      "dayNumber": 2,
      "startHours": "08:00",
      "endHours": "10:00"
    },
    {
      "dayNumber": 3,
      "startHours": "11:00",
      "endHours": "16:00"
    }
  ],
  "2023 - 01 - 01": [
    {
      "dayNumber": 5,
      "startHours": "05:00",
      "endHours": "10:00"
    },
    {
      "dayNumber": 7,
      "startHours": "19:00",
      "endHours": "22:00"
    }
  ]
}
';

然后,我们可以这样运行代码:

//I'm assuming that the json only contains availabilities for 1 user
//This creates an associated array out of your json
$assocArray = json_decode($jsonString, true);
$totalAvailabilityInMinutes = 0;
foreach($assocArray as $updatedAvailabilityAt => $availabilityArray) {
    $availabilityOfDayInMinutes = 0;
    foreach($availabilityArray as $availability) {
        $explodedStart = explode(':', $availability['startHours']);
        $explodedEnd = explode(':', $availability['endHours']);
        //Perform calculation from my comment
        $availabilityOfDayInMinutes = ($explodedEnd[0] * 60 + $explodedEnd[1]) - ($explodedStart[0] * 60 + $explodedStart[1]);
        dump("Availability of day {$availability['dayNumber']}: $availabilityOfDayInMinutes");
        $totalAvailabilityInMinutes += $availabilityOfDayInMinutes;
    }
}
dump($totalAvailabilityInMinutes);

请注意,我使用了两个变量来存储分钟数,一个是每天的,另一个是累积天数,您可以选择哪个变量最适合您。
我已经在本地测试了代码,它应该工作,并提供正确的数字;)

编辑:

因此,既然您已经有了一个数组,而不是一个JSON,那么您可以跳过这一步:

$assocArray = json_decode($jsonString, true);

相关问题