如何使用PHP将对象推送到对象中的数组
我正在学习如何在php中使用对象和数组。我以前在php中有一个类别数组和一个按类别组织的对象数组:如何使用PHP将对象推送到对象中的数组,php,object,multidimensional-array,Php,Object,Multidimensional Array,我正在学习如何在php中使用对象和数组。我以前在php中有一个类别数组和一个按类别组织的对象数组: public function live_scenarios_by_category(){ $scenario_list = $this->scenarios_model->get_scenario_data(); if ($scenario_list){ $categories = array(); $scenarios_by_category = array
public function live_scenarios_by_category(){
$scenario_list = $this->scenarios_model->get_scenario_data();
if ($scenario_list){
$categories = array();
$scenarios_by_category = array();
$curCatIndex = -1;
$curCatName = NULL;
foreach ($scenario_list as $i=>$scenario){
$category_name = $scenario['t3'];
if ($curCatName != $category_name){
$curCatIndex+=1;
$categories[$curCatIndex] = $category_name;
$curCatName = $category_name;
}
$scenarios_by_category[$curCatIndex][] = $scenario;
}
$data['categories'] = $categories;
$data['scenarios_by_category'] = $scenarios_by_category;
$this->load->view('data/json_scenarios', $data);
}
}
然后,我可以成功输出类别或按类别输出场景:
echo json_encode($categories);
或
但我想让“类别”数组变成一个由每个类别组织的对象(场景)数组,形式如下:
[{name: "cat1", children: [{name: "scenario1"},{name: "scenario2"}...]}{name:"cat2", children: [...]}];
我尝试按如下方式修改代码:
public function live_scenarios_by_category(){
$scenario_list = $this->scenarios_model->get_scenario_data();
if ($scenario_list){
$categories = array();
$scenarios_by_category = array();
$curCatIndex = -1;
$curCatName = NULL;
foreach ($scenario_list as $i=>$scenario){
$category_name = $scenario['t3'];
if ($curCatName != $category_name){
$curCatIndex+=1;
//$categories[$curCatIndex] = $category_name;
$cat_obj = new stdClass;
$cat_obj->name = $category_name;
$cat_obj->children = array();
$categories[$curCatIndex] = $cat_obj;
$curCatName = $category_name;
}
array_push($categories[$curCatIndex]['children'],$scenario);
//$categories[$curCatIndex]['children'][] = $scenario;
}
$data['categories'] = $categories;
// $data['scenarios_by_category'] = $scenarios_by_category;
$this->load->view('data/json_scenarios', $data);
}
}
但是我得到了错误
Cannot use object of type stdClass as array
行中:
array_push($categories[$curCatIndex]['children'],$scenario);
哪里出错了?要访问php中的对象,请使用
->
您正在使用的[]
是一个数组
试着改变这个
array_push($categories[$curCatIndex]['children'],$scenario);
到
如果有关联数组,则可以转换为以下对象: 关联数组 将关联数组转换为Json对象 将Json对象转换为Json PHP(PHP中的对象)
和:
$object=(object)$array代码>太长了。好主意,这是另一个解决方案!
array_push($categories[$curCatIndex]['children'],$scenario);
array_push($categories[$curCatIndex]->children,$scenario);
$associateArray = array(
'name' => 'Beef',
'quantity' => 1,
'unit' => 'ks',
'unit_price' => 120
);
$JsonObject = json_encode($associateArray);
$JsonPhpObject = json_decode($JsonObject);
echo $JsonPhpObject->name;