如何使用数组数据集从MySQL数据库中获取数据

时间:2019-08-07 13:30:25

标签: codeigniter

我正在尝试使用数组中已有的数据从mysql数据库和php codeigniter中获取数据。但似乎做错了。

 $query = $this->db->query("select * from product_order where transaction_code='BfkA'");
            foreach ($query->result_array() as $row)
            {   
                $p_id = $row['product_id'];
                $this->db->join('product_order', 'product_order.product_id = products.product_id');
                $this->db->where('products.product_id', $p_id);
                $res=$this->db->get('products');
            }
                return $res->result_array();

我希望输出在我的桌子上像这样


<table border="1">
<tr> <td>Product Name</td> <td>Quantity</td> </tr>
<tr> <td>shoe</td> <td>1</td> </tr>
<tr> <td>bag</td> <td>4</td> </tr>
<tr> <td>watch</td> <td>3</td> </tr>
</table> 

but i get

<table border="1">
<tr> <td>Product Name</td> <td>Quantity</td> </tr>
<tr> <td>shoe</td> <td>1</td> </tr>
<tr> <td>shoe</td> <td>1</td> </tr>
</table> 

1 个答案:

答案 0 :(得分:0)

您可以使用where_in来替换where方法,并使用array_column来获取 product_id 数组,然后可以删除foreach阻止:

$query = $this->db->query("select product_id from product_order where transaction_code='BfkA'");
$prod_ids = array_column($query->result_array(), 'product_id');

$this->db->join('product_order', 'product_order.product_id = products.product_id');
$this->db->where_in('products.product_id', $prod_ids);
$res = $this->db->get('products');
return $res->result_array();