Jam
Jam

Reputation: 197

php adding elements to array not working

I'm inserting elements dinamically in array, elements are inserted OK, but only the last one

I think that push_array will solve the problem, and I try

array_push($rowsItemAddit, $rowsItemAddit["item"]["acId"], $precio_row_addit->acId);

But I get error

Notice: Undefined index: item

My code working for the last element is

foreach($precios_row_addit as $precio_row_addit){
    $rowsItemAddit["item"]["acId"] = $precio_row_addit->acId;
    $rowsItemAddit["item"]["acValues"]  = array ( 'acValue' => $precio_row_addit->acValue );                    
    }

Any ideas to get the complete array?

The final structure should be:

[additionalColumnValues] => Array
    (
        [item] => Array
            (
                [acId] => 0
                [acValues] => Array
                    (
                        [acValue] => 10
                    )

            )
        [item] => Array
            (
                [acId] => 1
                [acValues] => Array
                    (
                        [acValue] => 10
                    )

            )               
        [item] => Array
            (
                [acId] => etc.
                [acValues] => Array
                    (
                        [acValue] => 10
                    )

            )
    )

        )

)

TIA

Upvotes: 0

Views: 70

Answers (2)

meda
meda

Reputation: 45490

You need to code it like this

foreach ($precios_row_addit as $precio_row_addit) {
    $rowsItemAddit[] = array('item' => array(
            'acId' => $precio_row_addit->acId,
            'acValues' => array('acValue' => $precio_row_addit->acValue)
        ));
}

Upvotes: 1

Mark Labenski
Mark Labenski

Reputation: 321

You always try to overwrite the same array elements. It can't have multiple keys named "item"

Try something like this, where the item index is an numeric index rather than "item":

foreach($precios_row_addit as $precio_row_addit){
    $rowsItemAddit[]["acId"] = $precio_row_addit->acId;
    $rowsItemAddit[]["acValues"] = array ( 'acValue' => $precio_row_addit->acValue );                    
}

Upvotes: 0

Related Questions