在这个codeigniter模型中,我试图推送每个产品的类别名称。 我希望数组看起来像:
Array
(
[0] => Array
(
[id] => 1
[name] => Game 1!
[category_id] => 3
[category] => games //the category element is in the [0] array.
)
[1] => Array
(
[id] => 2
[name] => Game 2
[category_id] => 3
[category] => games
)
这是阵列现在的样子:
Array
(
[0] => Array
(
[category] => games //i want this to be in the [1] array
)
[1] => Array
(
[id] => 1
[name] => Game 1!
[category_id] => 3
)
[2] => Array
(
[category] => games
)
[3] => Array
(
[id] => 2
[name] => Game 2
[category_id] => 3
)
这是我的函数,它获取所有产品并将它们放入数组中。
function getAllProducts(){
$data=array();
$Q=$this->db->get('products');
if($Q->num_rows() > 0){
foreach($Q->result_array() as $row){
$Q2=$this->db->query("select name FROM categories
where id={$row['category_id']}");
if($Q2->num_rows() > 0){
foreach($Q2->result_array() as $row2){
//Trouble Here: dont know how to push this into the array.
//is there a function that i can put in the $data[___]
//area so that it knows it is in the [0] element, then [1],etc?
$data[]['category']=$row2['name'];
}
}
$data[]=$row;
}
}
$Q->free_result();
return $data;
}
答案 0 :(得分:3)
要么:
foreach($Q->result_array() as $key=>$row){
$data[$key]=$row;
$Q2=$this->db->query("select name FROM categories
where id={$row['category_id']}");
if($Q2->num_rows() > 0){
foreach($Q2->result_array() as $row2){
$data[$key]['category']=$row2['name'];
}
}
}
甚至更好,做出正确的查询:
function getAllProducts(){
$data=array();
$Q=$this->db->query("SELECT p.*, c.name as category FROM products p, LEFT JOIN categories c ON c.id=p.category_id");
if($Q->num_rows() > 0){
foreach($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result(); // <- needed here? don't know
return $data;
}
我不知道CodeIgniter,所以我不知道这是否完全正确。但总的来说这要好得多,因为你减少了始终良好的数据库访问次数
这样,如果您有n+1
个产品,则只有一个查询而不是n
。
P.S。:我敢打赌CodeIgniter还提供了一些API来制作JOIN
。阅读documentation。
我刚看到,你可以这样做:
$this->db->select('*');
$this->db->from('products');
$this->db->join('categories', 'categories.id = products.category_id', 'left');
$Q = $this->db->get();
使用API。
答案 1 :(得分:1)
我会尝试一种不同的方法来减少您需要进行的总查询次数。
$productRows = getAllProducts();
$categoryRows = getAllCategories();
$categoriesById = array();
foreach ($categoryRows as $categoryRow) {
$categoriesById[$categoryRow['id']] = $categoryRow;
}
$productsWithCategory = array();
foreach ($productRows as $productRow) {
$categoryId = $productRow['category_id'];
$productsWithCategory[] = array(
'id' => $productRow['id'],
'name' => $productRow['name'],
'category_id' => $categoryId,
'category' => $categoriesById[$categoryId]['name']
);
}