我目前正在开发一个基于codeigniter构建的网站,我目前正在查询数据,我认为可能有3个数组可以作为数组返回,每个数组都有不同的结果,我的问题我不能为我的生活循环通过我现在拥有的数组,
我的模型看起来像这样
public function get_special_backgrounds() {
$this->db->select('*');
$this->db->from('background');
$this->db->where('is_special', 1);
$query = $this->db->get();
return $query->result_array();
}
我的控制器
enter public function index() {
// $this->output->enable_profiler(TRUE);
$data = array();
if($query = $this->category_model->get_all_online()) {
$data['main_menu'] = $query;
}
$this->load->model('image_model');
/*
* Sort out the users backgrounds, basically do a check to see if there is a 'special' background
* if there is not a 'special' background then IF the user is logged in and has a background of there
* own show that one, if not show a generic one, if they are not logged in show a generic one
*/
$image = array();
if ($query = $this->image_model->get_special_backgrounds()) {
$image = $query;
}
$data = array_merge($data, $image);
die(print_r($data));
$this->load->view('home/main_page.php', $data);
}
获取返回的数组看起来像这样,
Array
(
[main_menu] => CI_DB_mysql_result Object
(
[conn_id] => Resource id #28
[result_id] => Resource id #35
[result_array] => Array
(
)
[result_object] => Array
(
)
[current_row] => 0
[num_rows] => 1
[row_data] =>
)
[special] => Array
(
[0] => Array
(
[background_id] => 6
[background_name] => Master-Backgrounds.png
[background_path] => /Users/Simon/Sites/mysite/media/uploads/backgrounds/
[is_special] => 1
[background_date_uploaded] => 1262687809
[users_user_id] => 1
[users_user_group_group_id] => 1
)
[1] => Array
(
[background_id] => 11
[background_name] => Master-mysite-Template.png
[background_path] => /Users/Simon/Sites/mysite/media/uploads/backgrounds/
[is_special] => 1
[background_date_uploaded] => 1262795313
[users_user_id] => 5
[users_user_group_group_id] => 2
)
)
)
1
答案 0 :(得分:3)
它是一个对象,所以你不能像数组一样遍历它。我确实看到你正在尝试做什么,并理解为什么它似乎有意义,但要看到我在说什么,试试这个:
改变这个:
public function get_special_backgrounds() {
$this->db->select('*');
$this->db->from('background');
$this->db->where('is_special', 1);
$query = $this->db->get();
return $query->result_array();
}
对此:
public function get_special_backgrounds() {
$this->db->select('*');
$this->db->from('background');
$this->db->where('is_special', 1);
$query = $this->db->get();
return $query;
}
和
改变这个:
$image = array();
if ($query = $this->image_model->get_special_backgrounds()) {
$image = $query;
}
对此:
if($images = $this->image_model->get_special_backgrounds()) {
foreach($images->result_array() as $image) {
echo "<pre>";
print_r($image);
echo "</pre></br >";
}
}
答案 1 :(得分:2)
您是否需要循环数组的special
部分?
foreach ( $data['special'] as $row ) {
// do stuff with the $row array
}
答案 2 :(得分:1)
尝试foreach
$arr = (your array);
foreach ($arr as $key => $insideArrays) {
foreach ($insideArrays as $k2 => $insideInsideArrays){
..........
}
}
答案 3 :(得分:0)
看起来像一个结果数组,开头有一个奇数元素。我将摆脱第一个元素,然后循环遍历它:
array_shift($data);
foreach ($data as $row) {
// Do stuff with $row
var_dump($row);
}