【问题标题】:please i just want to know how can i get the first value from the array list as id only请我只想知道如何从数组列表中获取第一个值作为 id
【发布时间】:2019-09-16 01:33:40
【问题描述】:

控制器

$data['userInfo'] = $this->user_model->get15();

用户模型

function get15()
    {

        $this->db->select('userId');
        $this->db->from('tbl_security');
        $this->db->order_by('userId','ASC');
        $this->db->where('status', 0);
        $query = $this->db->get();
        $result = $query->result_array();
        return $result;
    }

我得到的数组

array(1) { [0]=> array(1) { [0]=> array(1) { ["userInfo"]=> array(7) { [0]=> array(1) { ["userId"]=> string(2) "15" } [1]=> array(1) { ["userId"]=> string(2) "17" } [2]=> array(1) { ["userId"]=> string(2) "18" } [3]=> array(1) { ["userId"]=> string(2) "19" } [4]=> array(1) { ["userId"]=> string(3) "178" } [5]=> array(1) { ["userId"]=> string(4) "1444" } [6]=> array(1) { ["userId"]=> 字符串(5) "12778" } } } } }

【问题讨论】:

    标签: php arrays codeigniter


    【解决方案1】:

    你可以使用array_column()

    $user_ids = array_column($data[0][0]['userInfo'], 'userId');
    print_r($user_ids);
    

    输出:

    array(15,17,18,19,178,1444,12778);
    

    【讨论】:

    • 感谢回复我收到此错误“遇到 PHP 错误严重性:通知”和严重性:警告消息:array_column() 期望参数 1 为数组,给定消息为空消息:未定义偏移量:0
    • 这只是一个警告,您的数组为空,您可以简单地使用 if 语句仅在数组不为空时运行该函数,例如if(!empty($data[0][0]['userInfo'])){ $user_ids = array_column($data[0][0]['userInfo'], 'userId'); } 如果您想遍历第一个两个嵌套数组,您将不得不遍历数组。
    • 再次感谢我得到了这些字符串 (26) "15,17,18,19,178,1444,12778"
    • @KishanChandra 如果您只需要整个数组中的第一个 id,那么您不需要上面的代码,在从模型获取结果后执行此操作,echo $data[0][0]['userInfo'][0]['userId'];
    • 如果这个答案能解决您的问题,请接受并投票。谢谢你。祝你有美好的一天。
    【解决方案2】:

    只需修改您的模型,如下所示。此代码将为您提供第一个数组数据。它与代码 $statement->fetch(PDO::FETCH_OBJ) 相同。编写下面的代码并修改它。

    function get15()
        {
    
            $this->db->select('userId');
            $this->db->from('tbl_security');
            $this->db->order_by('userId','ASC');
            $this->db->where('status', 0);
            $query = $this->db->get();
            $result = $query->row();
            return $result;
        }
    

    【讨论】:

    • 感谢您的回复,我如何从数组中获取 id。
    • 您正在从该方法获得响应。然后保留一个变量和。使用该变量打印 userid 。回显 $data->userId。这里的 data 是一个变量,用于保留方法中的数组
    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多