我想从3个mysql表(sections / rubriques / category)创建一个包含3个维度的数组:
[0] section_title_1
[0] rubrique_title_1
[0] category_title_1
[1] category_title_2
[2] category_title_3
[1] rubrique_title_2
...................
[1] section_title_2
.........
这是我的代码:
$output = array();
$i = 0;
$sections=$this->_model->get_table_sections();
foreach($sections as $section){
output[$i] = $section->section_title;
$ii = 0;
$rubriques = $this->_model->get_rubriques_for_a_section($section- >section_id);
foreach($rubriques as $rubrique){
$output[$i]['rubr'][$ii] = $rubrique->rubrique_title;
$iii = 0;
$categories = $this->_model->get_categ_for_a_section_and_a_rubrique($section->section_id,$rubrique->rubrique_id);
foreach($categories as $categorie){
$output[$i]['rubr'][$ii]['categories'][$iii] = $categorie->categorie_title;
$iii++;
}
$ii++;
}
$i++;
}
var_dump($output);
声明:$ output [$ i] ['rubr'] [$ ii] = $ rubrique-> rubrique_title;
i get an error of Illegal string offset 'rubr'
你能给我这个编码的答案吗?
非常感谢..
答案 0 :(得分:0)
您收到错误,因为$output[$i]
未定义且 Array 没有原型。所以,你可以通过将它初始化为空数组来解决它:
$output[$i] = array();
但是,你有错误,这段代码可以解决你的问题:
$output = array();
$i = 0;
$sections=$this->_model->get_table_sections();
foreach($sections as $section){
$output[$i]['title'] = $section->section_title;
$ii = 0;
$rubriques = $this->_model->get_rubriques_for_a_section($section- >section_id);
foreach($rubriques as $rubrique){
$output[$i]['rubr'][$ii] = $rubrique->rubrique_title;
$iii = 0;
$categories = $this->_model->get_categ_for_a_section_and_a_rubrique($section->section_id,$rubrique->rubrique_id);
foreach($categories as $categorie){
$output[$i] = isset( $output[$i] ) ? $output[$i] : array();
$output[$i]['rubr'] = isset( $output[$i]['rubr'] ) ? $output[$i]['rubr'] : array();
$output[$i]['rubr'][$ii] = isset( $output[$i]['rubr'][$ii] ) ? $output[$i]['rubr'][$ii] : array();
$output[$i]['rubr'][$ii]['categories'] = isset( $output[$i]['rubr'][$ii]['categories'] ) ? $output[$i]['rubr'][$ii]['categories'] : array();
$output[$i]['rubr'][$ii]['categories'][$iii] = isset( $output[$i]['rubr'][$ii]['categories'][$iii] ) ? $output[$i]['rubr'][$ii]['categories'][$iii] : array();
$output[$i]['rubr'][$ii]['categories'][$iii] = $categorie->categorie_title;
$iii++;
}
$ii++;
}
$i++;
}
var_dump($output);
答案 1 :(得分:0)
这可能是这样的:
$output = array();
$sections = $this->_model->get_table_sections();
foreach($sections as $section){
$output[$section->section_title] = array();
$rubriques = $this->_model->get_rubriques_for_a_section($section->section_id);
foreach($rubriques as $rubrique){
$output[$section->section_title][$rubrique->rubrique_title] = array();
$categories = $this->_model->get_categ_for_a_section_and_a_rubrique($section->section_id,$rubrique->rubrique_id);
foreach($categories as $categorie){
$output[$section->section_title][$rubrique->rubrique_title][] = $categorie->categorie_title;
}
}
}
var_dump($output);
使用标题作为索引。当然,只有当你不需要数字索引时,我才认为你不需要数字索引。