如何从多个嵌套的if条件中调用json [英] How to call json from multiple nested if condition

查看:121
本文介绍了如何从多个嵌套的if条件中调用json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CodeIgniter.我正在做一个小项目,它是一个批处理列表.现在,如果管理员要创建批次列表,则应输入开始日期和结束日期以及开始时间和结束时间,那么它将在数据库中检查该批次在相同的日期和时间运行吗?如果是,则显示消息,否则将创建新的批次列表.

I am using CodeIgniter. I am working on the small project which is a Batch list. Now If an admin wants to create the batch list then should enter the start date and end date and start time and end time then it will check in the database that batch is running on the same date and time? If yes then it will display the message if not then it will create a new batch list.

如果日期相同,则时间应该不同.

If the date is the same the time should be different.

现在我的逻辑是, 我正在将第一个new_start_date与exist_start_date和exist_end_date进行比较,如果发现之间的日期,它将检查时间.

Now My logic is, I am comparing the first new_start_date with exist_start_date and exist_end_date if date found in between then it will check the time.

它一直工作到比较为止.即使它正在检查时间,但从那里如何退出流程并调用JSON?因为从那里我的JSON无法正常工作.

It's working till date compare. Even it's checking the time but from there how to exit the process and call the JSON? because from there my JSON not working.

我从那里添加了"echo "time not match";",我无法调用JSON,但在网络标签上却得到了输出.

I added "echo "time not match";" from there I am not able to call the JSON I am getting the output on my network tab.

我正在获取输出

enter 1enter 2{"error":true,"msg":"Batch Created"}time not match

您能帮我这个忙吗?

 $id                         = $this->input->post('venue_id');
    $venue_id                   = implode(',',$id);     
    $activity_list_id           = $this->input->post('activity_name');
    $new_batch_start_date       = date('Y-m-d',strtotime($this->input->post('start_date')));    
    $new_batch_end_date         = date('Y-m-d',strtotime($this->input->post('end_date')));
    $new_batch_start_time       = $this->input->post('start_time');
    $new_batch_end_time         = $this->input->post('end_time');
    $days                       = implode(',',$this->input->post('days'));
    //print_r($days);   

    if($new_batch_start_date >= $new_batch_end_date)
    {
      $response['error'] = false;
      $response['msg']   = "End Date Should be Greater than Start Date";
      echo json_encode($response);
      return false;
    }

    //convert in Time Format
      $new_batch_start_time = strtotime($new_batch_start_time);   
      $new_batch_end_time = strtotime($new_batch_end_time);

      $venue = $this->input->post('name');
      $data = array(      
          'activity_list_id' => $this->input->post('activity_name'),          
          'batch_venue_id'   => $venue_id,      
          'batch_name'       => $this->input->post('batch_name'),     
          'start_date'       => date('Y-m-d',strtotime($this->input->post('start_date'))),     
          'end_date'         => date('Y-m-d',strtotime($this->input->post('end_date'))),     
          'start_time'       => $this->input->post('start_time'),     
          'end_time'         => $this->input->post('end_time'),     
          'total_capacity'   => $this->input->post('total_capecity'),
          'batch_status'     => 1,
          'created_by'       => trim($this->session->userdata['login_data']['user_id']),
          'created_date'     => date('d-m-Y h:i:s A'),
          'batch_days'     => $days
          );


    $get_batch_details = $this->Batch_model->fetchBatches(); 
    if(!empty($get_batch_details))
    {
      foreach ($get_batch_details as $rows)
      {
        $exist_batch_start_date =  $rows->start_date;
        $exist_batch_end_date =  $rows->end_date;
        $batch_time1 =  strtotime($rows->start_time);
        $batch_time2 =  strtotime($rows->end_time);
        $batch_venue_id = explode(',',$rows->batch_venue_id);
        $common_venue_id = array_intersect($id,$batch_venue_id);
        //print_r($common_venue_id);
        if($common_venue_id)
        {
          echo "enter 1";
        //if new batch start date  between existing batch start date 
        if($exist_batch_start_date <= $new_batch_start_date && $exist_batch_end_date >= $new_batch_start_date ){ 

          echo "enter 2";
          if($batch_time1 <= $new_batch_start_time && $batch_time2 > $new_batch_start_time){
                 $msg = "Other Batch Alredy Running On from Date $batch_start_date to $exist_batch_end_date on Time : $batch_time1 to $batch_time2.
                    Please Change Time Slot or Start And End Date"; 
                  $response['error'] = false;
                  $response['msg']   = $msg;
                  echo json_encode($response);
                  exit;
            }
            else{
              $result = $this->Batch_model->createBatch($data);
              echo "time not match";
              print_r($result);
            }
            break;
      }

     //if date is different 
 else 
    {
      $result = $this->Batch_model->createBatch($data);
    }    
}else 
    {
      $result = $this->Batch_model->createBatch($data);
    }
}
}
//first time creating batch
else 
    {
      $result = $this->Batch_model->createBatch($data);
    }

Mobel

function createBatch($data){
        if($this->db->insert('batch_list',$data))
            {
                $response['error'] = true;
                $response['msg']   = "Batch Created";
                echo json_encode($response);
            }
            else 
            {
                $response['error'] = true;
                $response['msg']   = "Failed to Create Batch";
                echo json_encode($response);
            }                   
    }

function fetchBatches()
    {
    $result = $this->db->where(['batch_list.batch_status'=>1,'activity_list.act_status'=>1])
                            ->from('batch_list')
                            ->join('activity_list','activity_list.activity_id = batch_list.activity_list_id')
                            ->get()
                            ->result();
        return $result;
    }

Ajax

success: function(response){
                    var data = JSON.parse(response);
                    if (data.error == true){                        
                        swal({
                             title: "Success", 
                             text: data.msg ,
                             type: "success"
                             }).then(function(){ 
                                location.reload();
                            }
                    );
                    } else {
                        swal({  
                            title: "Warning",                       
                             text: data.msg ,
                             type: "warning"
                            });
                    }
         }

您能帮我解决这个问题吗?

Would you help me out in this issue?

推荐答案

您的整个方法有点混乱,因为您发现自己陷入了大量的冗余代码片段中,却没人能完全理解您真正想要的是什么-我为您提供一些帮助这里的提示,包括基于您的代码的示例

your entire approach is a bit messy because you find yourself in a ton of redundant code fragments and nobody is able to understand what exactly you want - i gv you some hints here including an example based on your code

  1. 使用例外情况-非常适合您的情况-如果出现问题,请停止
  2. 尝试在一个任务的范围内过滤您的需求,并尝试解决该问题-仅在此之后转到下一个任务
  3. 始终-永远记住-考虑一个术语-如果您在应用程序中发现重复相同的代码-您知道出了点问题-并且您应该重构它-不要为裁员感到羞耻-裁员总是会发生的-但是如果您发现裁员,则必须重构这些代码段
  1. Use Exceptions - it's perfect for your case - if something goes wrong - stop it
  2. Try to filter your need to an extent of one single task und try to solve it - and only after that go to the next task
  3. Always - remember always - think about one term - if you find repeatedly the same code in your application - you know something is wrong - and you should refactor it - don't be ashamed about redundancies - they do always happen - but if you find them, you must refactor those code snippets

现在来看您的示例

您在这里做什么?

  • 您可以尝试询问您的数据库是否已在运行批处理-您无需遍历整个表条目
  • 比较来自管理员的两个输入日期-如果开始日期晚于结束日期,请立即停止应用程序
  • 您的交叉点对我来说不是很清楚,但是我很确信你也可以在这里询问数据库(流行语:find_in_set)

基于这些信息,我们现在就可以开始进行开发;)(如果我还没有掌握所有内容,只需完成上面的列表并尝试执行您的任务即可)

Based on that information we can start to develop things now ;) (if i don't have everything just complete the list above and try to implement your task)

控制器:

try
{
    $id = $this->input->post('venue_id');
    $venue_id = implode(',',$id);     
    $activity_list_id = $this->input->post('activity_name');
    $new_batch_start_date = date('Y-m-d',strtotime($this->input->post('start_date')));    
    $new_batch_end_date = date('Y-m-d',strtotime($this->input->post('end_date')));
    $new_batch_start_time = $this->input->post('start_time');
    $new_batch_end_time = $this->input->post('end_time');
    $days = implode(',',$this->input->post('days'));

    $objDateStart = DateTime::createFromFormat('Y-m-d h:i a', $new_batch_start_date.' '.$new_batch_start_time);
    $objDateEnd = DateTime::createFromFormat('Y-m-d h:i a', $new_batch_end_date.' '.$new_batch_end_time);

    if ($objDateEnd < $objDateStart)    throw new Exception('End Date Should be Greater than Start Date');

    if ($this->Batch_model->hasBatchesBetweenDates($objDateStart, $objDateEnd)) throw new Exception('Other Batch already running On from '.$objDateStart->format('d-m-Y H:i').' to '.$objDateEnd->format('d-m-Y H:i').'. Please Change Time Slot for Start and End Date'); 

    $data = array(      
        'activity_list_id' => $this->input->post('activity_name'),          
        'batch_venue_id'   => $venue_id,      
        'batch_name'       => $this->input->post('batch_name'),     
        'start_date'       => $objDateStart->format('Y-m-d'),     
        'end_date'         => $objDateEnd->format('Y-m-d'),     
        'start_time'       => $objDateStart->format('H:i'),     
        'end_time'         => $objDateEnd->format('H:i'),     
        'total_capacity'   => $this->input->post('total_capecity'),
        'batch_status'     => 1,
        'created_by'       => trim($this->session->userdata['login_data']['user_id']),
        'created_date'     => date('d-m-Y h:i:s A'),
        'batch_days'     => $days
    );

    $this->Batch_model->createBatch($data);
}
catch(Exception $e)
{
    $arrError = [
        'error' => false,
        'msg' => $e->getMessage()
    ];

    echo json_encode($arrError);
}

型号:

public function hasBatchesBetweenDates(DateTime $objDateStart, DateTime $objDateEnd)
{
    $query = $this->db
    ->from('batch_list')
    ->join('activity_list','activity_list.activity_id = batch_list.activity_list_id')
    ->where('CONCAT(start_date,\' \',start_time)  >=', $objDateStart->format('Y-m-d H:i:s'))
    ->or_group_start()
        ->where('CONCAT(end_date, \' \', end_time) <=', $objDateEnd->format('Y-m-d H:i:s'))
        ->where('CONCAT(end_date, \' \', end_time) >=', $objDateStart->format('Y-m-d H:i:s'))
    ->group_end()
    ->get();

    return ($query->num_rows() > 0);
}

我希望您理解这里的概念-如果您有任何疑问-请不要犹豫地询问

i hope you understand the concepts here - if you've questions - don't hesitate to ask

这篇关于如何从多个嵌套的if条件中调用json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆