此查询的更好解决方案

时间:2018-11-04 22:25:44

标签: php codeigniter

$query = $this->db->query("SELECT field_name FROM table_name;");

        $getData= array();

        foreach ($query->result() as $row) {

            array_push($getData, $row->field_name);
        }

我使用codeigniter,对于需要管理数据是否存在以进行更新或进行新插入的每个表,我都使用此代码,因此我希望看到有更多选项可用于每次都不复制代码。我只是一个学生,对不起英语!

2 个答案:

答案 0 :(得分:0)

不清楚为什么要这样做,但是我称其为“扁平化”数组。如果您发现经常需要这样做,那么创建“工作者”方法可能会有所帮助。

例如,在模型中,您可能有两种方法都需要“平坦”结果。

public function get_something()
{
    $query = $this->db->query("SELECT field_name FROM table_name;");
    //call the "worker"
    return $this->make_flat($query);
}

public function get_something_else()
{
    $query = $this->db->query("SELECT field_name FROM table_name;");
    //call the "worker"
    return $this->make_flat($query);
}

在模型的其他地方,上面的代码中使用了这种“工人”方法。

// The "worker" method to flatten the results
protected function make_flat($query)
{
    $getData = []; //is same as $getData = array(); but with less typing
    foreach ($query->result() as $row)
    {
        $getData[] = $row->field_name;
    }
    return $getData;
}

$getData[] = $row->field_name;行与array_push($getData, $row->field_name);完全相同。但这实际上要快一些。打字也少了。

答案 1 :(得分:0)

http://php.net/manual/en/function.array-column.php应该很好用。

$query = $this->db->query("SELECT field_name FROM table_name;");

$array = array_column($query, 'field_name');

print_r($array);

您的问题似乎与您的代码矛盾。如果您只想查看特定条目是否已存在,可以执行以下操作:

$this->db->where('field_name', $var);
$exists = $this->db->count_all_results('table_name');
if ($exists > 0) {
    // update
    // there is an entry with $var for `field_name` in table `table_name`
} else {
    // insert
}