如何在Codeigniter中使用php在if条件下编写JSON响应?

时间:2019-04-10 12:25:48

标签: php codeigniter jquery-select2

我已经在function控制器中编写了以下Categories。其中检查categories中的database并返回response。现在,如果parent_cat_id: "1",那么我想显示select2中的Form字段

public function parent_categories(){
        $table = "store_categories";
        $selectData = "id AS ID, cat_title AS TEXT,parent_cat_id";
        $search = $this->input->get('q');
        $where = array('status' => "enabled");
        if(isset($search) && !empty($search)){
            $field = "Title";
            $Result = $this->Common_model->select_fields_where_like_join($table,$selectData,"",$where,FALSE,$field,$search);
        }else{
            $Result = $this->Common_model->select_fields_where_like_join($table,$selectData,"",$where);
        }
        if(empty($Result)){
            $emptyArray = array(
                array(
                    'ID' => 0,
                    'TEXT' => "No Record Found"
                )
            );
            print json_encode($emptyArray);
            return;
        }
        print json_encode($Result);
    }
  

这是select2中的form字段

我已经尝试过类似的方法,但是我确信这是行不通的。我已将此<?php if(parent_cat_id == "1"){?>写给大家,以了解我在说如何在JSON response上执行类似操作

<?php if(parent_cat_id == "1"){?>
    <div class="col-md-4">
       <div class="form-group">
          <label for="Header Text" class="control-label">Parent Category</i>
          </label>
          <select name="parent_categories" id="parent_categories" class="form-control select2" ></select>
       </div>
       <!-- /.form-group -->
    </div>
 <?php } ?>
  

这是JSON响应

{  
    ID:"2",
    TEXT:"waqas",
    parent_cat_id:"1"
}

1 个答案:

答案 0 :(得分:0)

$emptyArray = array(
                array(
                    'ID' => 0,
                    'TEXT' => "No Record Found"
                )
            );

$json = json_decode(json_encode($emptyArray));
echo $json->parent_cat_id;

首先,您需要使用json_decode而不是encoding才能使用json数据。 Json解码会将其变成您的对象或关联数组,然后您可以根据需要使用它。