Question

I have the following PHP code:

$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;
        }

The problem is that in the foreach loop if there are multiple items with the same $row->table_id then the last one in the loop is set (ignoring all others). I have tried the !isset($alignments->{row->table_id}) and it is still overriding. I am trying to say that if the variable of $alignments->{$row->table_id} exists, use it, if not, set it to a new StdClass()

Was it helpful?

Solution

Maybe you need to wrap your initialization like this:

if (!property_exists($alignment, $row->table_id)) {
  $alignments->{$row->table_id} = new StdClass();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top