【问题标题】:How to write JSON Response in if condition using php in codeigniter?如何在codeigniter中使用php在if条件下编写JSON响应?
【发布时间】:2019-04-10 12:25:48
【问题描述】:

我在Categories 控制器中编写了以下function。检查database 中的categories 并返回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);
    }

这是form 中的select2 字段

我已经尝试过类似的方法,但我确信这不起作用。我写了这个<?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"
}

【问题讨论】:

  • 我认为您的问题不清楚,请在这里更具体

标签: php codeigniter jquery-select2


【解决方案1】:
$emptyArray = array(
                array(
                    'ID' => 0,
                    'TEXT' => "No Record Found"
                )
            );

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

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

【讨论】:

  • 它不起作用。 select2 字段在视图中我如何在 if 语句中检查它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-31
  • 2011-12-23
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多