将项添加到foreach内的数组中

时间:2017-05-23 07:16:33

标签: php

我想知道如何在数组末尾添加项目,我已经尝试了很多,但我不能。

$arr = [
    'shopping_cart' => [
        'items' => [
            0 => [
                'item_id' => 22161,
                 'item_price' => 24.99,
                 'item_url' => '',

            ],
        ]
    ]
];

我试过这段代码,但是没有用,它不是添加新索引,而是在已经存在的索引中创建新索引。

 foreach($arr['shopping_cart']['items'] as $index => &$value) {         


      array_push($value, [$index => 'test']);  

       echo '<pre>';
       print_r($value);
   }

// Result in
Array
  (
    [item_id] => 1
    [item_price] => 24.99
    [item_url] => 
    [0] => Array
     (
        [0] => test
     )

)
// I want to create new index with different data, keeping the index that already exists.


Array
   (
     [item_id] => 1
     [item_price] => 24.99
     [item_url] => 

 )

    Array
  (
    [item_id] => 2
    [item_price] => 34.99
    [item_url] => 

)

有人可以解释我做错了什么吗?

3 个答案:

答案 0 :(得分:2)

无需迭代数组,只需添加值:

$arr['shopping_cart']['items'][] = [
   'item_id' => 22162,
   'item_price' => 34.99,
   'item_url' => '',   
];

答案 1 :(得分:0)

试试这个希望这会帮助你。用于添加新数据到索引。

Try this code snippet here

<?php

ini_set("display_errors", 1);
$arr = [
'shopping_cart' => [
    'items' => [
        0 => [
            'item_id' => 22161,
             'item_price' => 24.99,
             'item_url' => '',

        ],
]]];
$arr['shopping_cart']['items'][]=array(
   'item_id' => 22162,
   'item_price' => 34.99,
   'item_url' => '');

print_r($arr);

答案 2 :(得分:0)

array_push($value, [$index => 'test']);更改为$value[$index] = 'test' ;