当通过id或代码搜索时,如何从mysql得到行索引导致codeignitier

时间:2018-04-03 11:55:42

标签: php mysql codeigniter

我有数据:

Array
(
    [0] => Array
        (
            [id] => 12
            [code] => 12345
            [name] => Aaron
        )
    [1] => Array
        (
            [id] => 5
            [code] => 16784
            [name] => Bryan
        )
    [2] => Array
        (
            [id] => 35
            [code] => 32467
            [name] => Charlie
        )
    [3] => Array
        (
            [id] => 25
            [code] => 44513
            [name] => Denise
        )
    [4] => Array
        (
            [id] => 44
            [code] => 15774
            [name] => Michael
        )
)

在我的模型中,我创建了函数:

private function getPosition($field_search, $field_value){ // ID or code        
    $this->db->select('*');
    $this->db->from($this->table);
    $this->db->order_by('name','asc');
    $result = $this->db->get()->result();
    $pos = array_search($field_value, array_column($result, $field_search));

    return ($pos !==false ? $pos : -1);
}

如果我想得到行索引“32467”,我只需要调用

$pos = $this->getPosition('code', '32467');

然后我得到的行索引是“2”,

但我想知道,如果查询是:

,如何获得行索引
$this->db->select('*');
$this->db->from($this->table);
$this->db->where('code', '32467');
$this->db->order_by('name','asc');
$result = $this->db->get()->result();

在我的问题中纠正了 我的意思是,如果我们在数据库中索引代码=“32467”,我们得到的索引是“2”,如果索引是“2”则如何获得返回

感谢您的帮助......

1 个答案:

答案 0 :(得分:0)

    <?php

    $userdb= Array
    (
        "0" => Array(
                'id' => "12",
                'code' => "12345",
                'name' => 'Aaron'
            ),

        "1" => Array
            (
                "id" => "5",
                "code" => "16784",
                "name" => "Bryan"
            ),
        "2" => Array
            (
                "id" => "35",
                "code" => "32467",
                "name" => "Charlie"
            ),
        "3" => Array
            (
                "id" => "25",
                "code" => "44513",
                "name" => "Denise"
            ),
        "4" => Array
            (
                "id" => "44",
                "code" => "15774",
                "name" => "Michael"
            ),
    );

    $key = array_search(32467, array_column($userdb, 'code'));

    echo ("The key is: ".$key);

private function getPosition($field_search, $field_value){ // ID or code        
    $this->db->select('*');
    $this->db->from($this->table);
    $this->db->order_by('name','asc');
    $result = $this->db->get()->result();
    $key = array_search($field_value, array_column($result, $field_search));
    return $key;
}
    ?>