dongtan8979 2017-09-18 10:44
浏览 47
已采纳

如何匹配数组中的值并在php中推送数组

Here below is my code.

I'm trying to plot graph values using the below array. On the dates array i have all 30 days in the array. I have another array called pending_date and approved_date. I need to match the date.Add the key and value for the matching key(date) array. Can u tell me where I'm going wrong ?

$approved_date = array('2017-09-01'=>'1','2017-09-02' => '2', '2017-09-03' => '4');
$pending_date = array('2017-09-01'=>'2');
$rejected_date = array();

Tried Code

        $myYearMonth = date('Y-m');
        $start = new DateTime(date('Y-m-01', strtotime($myYearMonth)));
        $end = new DateTime(date('Y-m-t', strtotime($myYearMonth)).' +1 day');
        $diff = DateInterval::createFromDateString('1 day');
        $periodStart = new DatePeriod($start, $diff, $end);

        foreach ( $periodStart as $dayDate ){
         $dates[]['period'] = $dayDate->format( "Y-m-d" );
        }

        foreach( $pending_date as $key => $value ){
          $data_key = array_search( $key, $dates );
          if( $data_key !== false ) $dates[ $data_key ] = $value;
        }

Expected Output

{"period": "2017-09-01", "approved": 1, "pending": 2, "rejected": 0},
{"period": "2017-09-02", "approved": 2, "pending": 0, "rejected": 0},
{"period": "2017-09-03", "approved": 4, "pending": 0, "rejected": 0}
  • 写回答

1条回答 默认 最新

  • doukuipei9938 2017-09-18 10:53
    关注

    Try something like this:

    $approved_date = array('2017-09-01'=>'1','2017-09-02' => '2', '2017-09-03' => '4');
    $pending_date = array('2017-09-01'=>'2');
    $rejected_date = array();
    
    $dates = array();
    //$periods = array_unique(array_merge(array_keys($approved_date), array_keys($pending_date), array_keys($rejected_date)));
    $periods = array(); // fill $periods how you like
    for($i=1; $i<=30; $i++) {
        $periods[] = '2017-09-' . str_pad($i, 2, '0', STR_PAD_LEFT);
    }
    foreach ($periods as $period) {
        $dates[] = array(
            'period' => $period,
            'approved' => isset($approved_date[$period]) ? $approved_date[$period] : 0,
            'pending' => isset($pending_date[$period]) ? $pending_date[$period] : 0,
            'rejected' => isset($rejected_date[$period]) ? $rejected_date[$period] : 0,
        );
    }
    
    echo json_encode($dates);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀