php添加元素到数组无法正常工作

时间:2014-11-25 18:10:22

标签: php arrays

我在数组中插入元素,元素插入OK,但只插入最后一个

我认为push_array会解决问题,我会尝试

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

但我收到错误

注意:未定义的索引:item

我为最后一个元素工作的代码是

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

获得完整阵列的任何想法?

最终结构应该是:

[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

2 个答案:

答案 0 :(得分:1)

你需要像这样编码

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

答案 1 :(得分:0)

您总是尝试覆盖相同的数组元素。 它不能有多个名为" item"

的键

尝试这样的事情,其中​​项目索引是数字索引,而不是"项目":

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