【问题标题】:help with matching array keys overwriting each other帮助匹配数组键互相覆盖
【发布时间】:2011-01-13 20:10:20
【问题描述】:

我遇到了从我正在运行的查询返回的数组的问题,

    $jobs = array(
  array('id'=>2,'salary'=>27000,'benefits'=>'false','benefits_description'=>'','skills'=>'PHP mysql javascript','job_summary'=>'Developing stuff','job_description'=>'Developing stuff','tags'=>'PHP, mysql, web development, web, leeds','created_at'=>1294871124,'updated_at'=>0,'job_titles_id'=>1,'locations_id'=>1,'employers_id'=>4,'id'=>1,'jobtitle'=>'Website Developer','id'=>1,'location'=>'Leeds')
);

我想在我正在构建的链接中使用第一个 id,但是它返回 1 而不是 2,因为我假设第一个 id 被数组中稍后的 ID 覆盖?有什么办法可以阻止这种情况的发生,在项目的这个阶段我无法更改我的数据库模式,从数据库中获取它的查询看起来像这样,

$this->db->select('*')
        ->from('jobs')
        ->join('job_titles', 'job_titles.id = jobs.job_titles_id', 'left')
        ->join('locations', 'locations.id = jobs.locations_id', 'left')
        ->where('jobs.employers_id', $employer_id);

        $query = $this->db->get();

        return $query->result_array();

【问题讨论】:

    标签: php arrays codeigniter activerecord


    【解决方案1】:

    您需要为从数据库中返回的字段设置别名。

    您尚未指定您使用的 RDBMS,但很可能是 MySQL,因此不要使用 SELECT *(老实说这是一种懒惰和不好的做法),您应该指定您特别需要并且可以使用以下形式为第二个 ID 字段设置别名:

    SELECT ... <table name>.<field name> AS id_2 ... FROM ...
    

    这里是相关的MySQL manual page 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2011-04-11
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2022-12-12
      相关资源
      最近更新 更多