为foreach循环中的缺失项创建零值

时间:2016-04-19 07:50:15

标签: php mysql arrays

我有一个应用程序,它在两个日期之间从mysql中提取一些信息并返回一个关联数组。我正在生成一个包含此信息的图表,但数据库中没有信息要返回的日期缺少日期。我无法在mysql端修复此问题,因为我只能读取数据库。

我的数据库方法检索如下所示的关联数组:

[0] => Array
        (
            [number_of_calls] => 151
            [total_call_time] => 00:01:30
            [average_call] => 00:02:00
            [DATE(calldate)] => 2016-03-18
            [direction] => outbound
        )

我希望做的是从我的表单创建一个日期范围,如下所示:

    //create data range array
    $begin = new DateTime( $datefrom );
    $end = new DateTime( $dateto );
    $end = $end->modify( '+1 day' );
    $interval = new DateInterval('P1D');
    $daterange = new DatePeriod($begin, $interval ,$end);

然后使用foreach循环迭代日期范围的选定日期,并从日期匹配的关联数组中提取值,如果不是,则插入零值,如下所示:

        [number_of_calls] => 0
        [total_call_time] => 00:00:00
        [average_call] => 00:00:00

我还需要最终数组以日期顺序结束。请有人帮帮我吗?

2 个答案:

答案 0 :(得分:1)

您可以将$result数组转换为使用DATE(calldate)作为键。

$keys = [];
foreach ($result as $item) {
    $keys[] = $item['DATE(calldate)'];
}
$result = array_combine($keys, $result);

你的阵列看起来像那样:

[2016-03-18] => Array
    (
        [number_of_calls] => 151
        [total_call_time] => 00:01:30
        [average_call] => 00:02:00
        [DATE(calldate)] => 2016-03-18
        [direction] => outbound
    )

您可以通过简单的命令检查日期是否显示:

$key = $datevalue->format('Y-m-d');
if (isset($result[$key])) {
    // date exists, use it
} else {
    // date not exists, create empty value
}

答案 1 :(得分:0)

这就是我最终做的事情

// helper function to recursively search array
        function recursive_array_search($needle,$haystack) {
            foreach($haystack as $key=>$value) {
                $current_key=$key;
                if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
                    return $current_key;
                }
            }
            return false;
        }


        foreach ($daterange as $datevalue) {

          $key = recursive_array_search($datevalue->format('Y-m-d'), $result);

          // if date is found write values from data to output array
          if ($key !== False) {
          $output_array[] = array("number_of_calls" => $result[$key]['number_of_calls'],
                "total_call_time" => $result[$key]['total_call_time'],
                "average_call" => $result[$key]['average_call'],
                "DATE(calldate)" => $datevalue->format('Y-m-d'),
                 "direction" => "outbound" );
               }
          // else write zeros
          else  {
            $output_array[] = array("number_of_calls" => "0",
                  "total_call_time" => "00:00:00",
                  "average_call" => "00:00:00",
                  "DATE(calldate)" => $datevalue->format('Y-m-d'),
                   "direction" => "outbound" );
          }

}

        $this->chart_data = $output_array;
    }