在這個codeigniter模型中,我試圖推送每個產品的類別名稱。 我想看看數組一樣:我該如何推送這個2-D數組? (PHP)
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;
}
你是一個天才。我不能相信我忽略了$ key => $行。非常感謝你。如果我見過你,我會給你買一瓶啤酒:) – ggfan 2010-06-21 20:14:30
@ggfan:好吧;)但**請**考慮第二種方法......它的性能明顯更好**。 – 2010-06-21 20:15:23
是的,先生,我會用第二種方法。 – ggfan 2010-06-21 20:17:08