【问题标题】:How to add multiple values to a key of an array and get data from another table?如何将多个值添加到数组的键并从另一个表中获取数据?
【发布时间】:2013-12-14 16:44:27
【问题描述】:

我正在尝试从一个数据库中获取数据,条件是 id 等于当前登录的租户 (tenant_id),

$this->data['props'] = $this->property_m->get_by( array ('id' => $this->session->userdata['tanant_id'] ));

然后从一个字段中获取一些值并保存在一个数组中,

if(count($this->data['props']) > 0){
    $my_array = array();
    foreach ($props as $prop){
        $my_array['id'] = $prop->tenant_id;
    }
}

这里的第一个问题 - $my_array 仅包含 1 个值。 (我需要它是多个)我该怎么做?
第二个问题 - 我需要从另一个表中选择数据,该表将在该数组中查找满足条件的数据,作为,

$this->data['reports'] = $this->report_m->get_by($my_array);

会说,

SELECT * FROM  reports WHERE ('id = 1'); // or 2 or 3 (value from prop->tenant)

但我需要它,

SELECT * FROM reports WHERE ('id = 1 OR id = 2 OR id = 3'); 

【问题讨论】:

  • 1.不要每次迭代都覆盖密钥id。 2.Where id IN ()
  • 请告诉我如何不覆盖密钥 id

标签: php arrays database codeigniter


【解决方案1】:

在做:

$my_array = array();
foreach ($props as $prop){
    $my_array['id'] = $prop->tenant_id;
}

您只是覆盖了$my_arrayid 键。使用这个:

$my_array = array();
foreach ($props as $prop){
    $my_array[] = $prop->tenant_id;
}
// print_r($my_array); 

使用where field in ()条件:

SELECT * FROM reports WHERE id IN (1, 2, 3);

假设你有:

$my_array = array(1,2,3);
// query string:
$q_str = 'SELECT * FROM reports WHERE id IN (' . implode(',', $my_array) . ')';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多