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

How to write JSON Response in if condition using php in codeigniter?

我在 Categories 控制器中写了以下 function。其中检查 database 中的 categories 和 returns 中的 response。现在,如果 parent_cat_id: "1" 那么我想显示 Form

中的 select2 字段
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);
    }

This is the select2 Field in 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 } ?>

This is the JSON Response

{  
    ID:"2",
    TEXT:"waqas",
    parent_cat_id:"1"
}
$emptyArray = array(
                array(
                    'ID' => 0,
                    'TEXT' => "No Record Found"
                )
            );

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

首先,您需要使用 json_decode 而不是编码,以便能够处理 json 数据。 Json 解码会将其转换为对象或关联数组,供您随意使用。