使用自定义标签和值将php sql结果数组格式更改为json格式

时间:2016-05-16 11:44:48

标签: php json codeigniter-3

我需要帮助转换这个json数据数组

{"Untracked":4,"Available":3,"Groups":"4","Users":"5"}

到这种类型的json

[{"label":"Untracked","value":"4"},
 {"label":"Available","value":"3"},
 {"label":"Groups","value":"4"},
 {"label":"Users","value":"5"}
]

我的方法是

public function graphs(){
    $company_id =$this->session->userdata('itms_company_id');
    $data['Untracked'] = $this->mdl_fetch->count_untracked_assets ($company_id);
    $data['Available'] = $this->mdl_fetch->count_available_devices ($company_id);
    $data['Groups'] = $this->mdl_fetch->count_unassigned_groups($company_id);
    $data['Users'] = $this->mdl_fetch->count_unassigned_users($company_id);

    echo json_encode($data);
}

4 个答案:

答案 0 :(得分:0)

试试这个:

public function graphs(){
    $company_id =$this->session->userdata('itms_company_id');
    $data[] = array( 'label' => 'Untracked', 'value' => $this->mdl_fetch->count_untracked_assets ($company_id));
    $data[] = array( 'label' => 'Available', 'value' => $this->mdl_fetch->count_available_devices ($company_id));
    $data[] = array( 'label' => 'Groups', 'value' => $this->mdl_fetch->count_unassigned_groups($company_id));
    $data[] = array( 'label' => 'Users', 'value' => $this->mdl_fetch->count_unassigned_users($company_id));

    echo json_encode($data);
}

答案 1 :(得分:0)

这是一种方式,但似乎有点长篇大论。

json stdClass()表示您需要一个对象,因此您可以使用简单的PHP mdl->fetch并添加相关属性并从$data&#返回的数组中获取数据39; s并加载对象。然后将其添加到public function graphs(){ $company_id = $this->session->userdata('itms_company_id'); $d = $this->mdl_fetch->count_untracked_assets ($company_id); $o = new stdClass(); $o->label = 'Untracked'; $o->value = $d['Untracked']; $data[] = $o; $d = $this->mdl_fetch->count_available_devices ($company_id); $o = new stdClass(); $o->label = 'Available'; $o->value = $d['Available']; $data[] = $o; $d = $this->mdl_fetch->count_unassigned_groups($company_id); $o = new stdClass(); $o->label = 'Groups'; $o->value = $d['Groups']; $data[] = $o; $d = $this->mdl_fetch->count_unassigned_users($company_id); $o = new stdClass(); $o->label = 'Users'; $o->value = $d['Users']; $data[] = $o; echo json_encode($data); } 数组。

./build/sbt

答案 2 :(得分:0)

无需更改整个功能。

12:1更改为echo json_encode($data);

创建一个函数,在调用return json_encode($data);函数后将格式从一个json更改为另一个函数,您可以调用另一个可以按需要返回json数据的函数

graph()

答案 3 :(得分:0)

这里是示例,它具有相同的输出

UIApplication.sharedApplication().keyWindow?.rootViewController.performSegueWithIdentifier("SegueIdentifier", sender: nil)

所以,你可以写一个这样的函数:

$a = array(); <br>
$a[0]['label'] = "Untracked"; <br>
$a[0]['value'] = "4"; <br>
$a[1]['label'] = "Available"; <br>
$a[1]['value'] = "3"; <br>
$a[2]['label'] = "Groups"; <br>
$a[2]['value'] = "4"; <br>
$a[3]['label'] = "Users"; <br>
$a[3]['value'] = "3"; <br>

$json= json_encode($a); <br>

<b>Output</b> <br>

[{"label":"Untracked","value":"4"},<br>{"label":"Available","value":"3"},<br>{"label":"Groups","value":"4"},<br>{"label":"Users","value":"3"}]<br>