我有以下 PHP 代码:
$alignments = new StdClass();
if ($query->num_rows > 0)
{
foreach($query->result() as $row){
$alignments->{$row->table_id} = new StdClass();
$alignments->{$row->table_id}->table_id = isset($row->table_id)?$row->table_id:NULL;
$alignments->{$row->table_id}->title = isset($row->title)?$row->title:NULL;
$alignments->{$row->table_id}->url = isset($row->url)?$row->url:NULL;
$alignments->{$row->table_id}->state_id = isset($row->state_id)?$row->state_id:NULL;
$alignments->{$row->table_id}->cross_discipline_alignment = isset($row->cross_discipline_alignment)?$row->cross_discipline_alignment:NULL;
$alignments->{$row->table_id}->common_core = isset($row->common_core)?$row->common_core:NULL;
$alignments->{$row->table_id}->grade_level = isset($row->grade_level)?$row->grade_level:NULL;
$alignments->{$row->table_id}->indicators = new StdClass();
$alignments->{$row->table_id}->indicators->{$row->indicator_id} = new StdClass();
$alignments->{$row->table_id}->indicators->{$row->indicator_id}->indicator_id = isset($row->indicator_id)?$row->indicator_id:NULL;
$alignments->{$row->table_id}->indicators->{$row->indicator_id}->indicator = isset($row->indicator)?$row->indicator:NULL;
$alignments->{$row->table_id}->indicators->{$row->indicator_id}->key = isset($row->key)?$row->key:NULL;
$alignments->{$row->table_id}->indicators->{$row->indicator_id}->extra_data = isset($row->extra_data)?$row->extra_data:NULL;
$alignments->{$row->table_id}->indicators->{$row->indicator_id}->uri_k5 = isset($row->uri_k5)?$row->uri_k5:NULL;
$alignments->{$row->table_id}->indicators->{$row->indicator_id}->uri_612 = isset($row->uri_612)?$row->uri_612:NULL;
}
return $alignments;
}
问题是,在 foreach 循环中,如果有多个相同的项目,$row->table_id
则设置循环中的最后一个(忽略所有其他项目)。我已经尝试过了!isset($alignments->{row->table_id})
,它仍然是压倒一切的。我想说如果变量$alignments->{$row->table_id}
存在,使用它,如果不存在,将其设置为new StdClass()