我们如何计算记录数并在rest api中显示?

时间:2019-05-30 10:38:07

标签: php json api codeigniter

控制器:

<?php
    require APPPATH . '/libraries/REST_Controller.php';
    use Restserver\Libraries\REST_Controller;
    class User extends REST_Controller 
    {   
        function country_get()
        {
            $this->db->select('id,name');
            $this->db->from('countries');
            $sql = $this->db->get();
            $result = $sql->result_array();
            $this->response($result, 200);
        }
    }

意外的输出:

[
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]

预期输出:

{
"Message": "Number of Country found: 5",
"Status": "Success",
"Country": [
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]

}

在此代码中,我希望显示预期数量的记录数。那么,我该怎么做?请帮助我。

谢谢

4 个答案:

答案 0 :(得分:2)

您的结果已经是一个数组,因此请使用PHP函数count()获取数组的长度:

function country_get()
{
   $this->db->select('id,name');
   $this->db->from('countries');
   $sql = $this->db->get();
   $result = $sql->result_array();

   $response = [
       "Message" => "Number of Country found: " . count($result),
       "Status" => "Success",
       "Country" => $result
   ];

   $this->response($response, 200);
}

答案 1 :(得分:0)

您可以将查询结果保存到数据中,

$result = [];
// save data
$data = $sql->result_array();
// save count into message
$result['Message'] = "Number of Country found:".count($data); // sizeof($data)
$result['Status'] = "Success";
// save actual data for country index
$result['Country'] = $data;
// return response to it
$this->response($result, 200);

count-计算数组中的所有元素或对象中的东西

sizeof-count()的别名

答案 2 :(得分:0)

尝试一下,无需使用count() CI,您已经可以在num_rows()中获得计数

function country_get()
{
     $this->db->select('id,name');
     $this->db->from('countries');
     $sql = $this->db->get();
     $count = $sql->num_rows();
     $result = array();
     $result['Message'] = "Number of Country found: " . $count;
     $result['Status'] = "Success";      
     $result['Country'] = $sql->result_array();
     $this->response($result, 200);
}

答案 3 :(得分:0)

用以下代码替换您的函数:

function country_get()
   {
         $this->db->select('id,name');
         $this->db->from('countries');
         $sql = $this->db->get();
         $res = $sql->result_array();
         $result['Status'] = "Success";
         $result['Message'] = "Total country found ".count($res);
         $result['Country'] = $res
         $this->response($result, 200);
    }