1

How can i push variable into multidimensional array php? when I give key for the tow array it worked, but when I delete keys it doesn't work : I mean :

$array1= array('x'=>array('id'=>7,'code'=>4444),'y'=>array('id'=>8,'code'=>3333));
whith
array_push($array1['x'],$newdata); 

I dont want to generate x, y ... , I want let it automatically generated.

I want a result look like that:

Array
(
    [0] => Array
        (
            [id] => 7
            [code] => 4444
            [newData] => 1111
        )

    [1] => Array
        (
            [id] => 8
            [code] => 3333
            [newData] => 1111
        )

)

Here what i tried:

<?php
$array1= array(array('id'=>7,'code'=>4444),array('id'=>8,'code'=>3333));
$newdata = 1111;
foreach ($array1 as $item ){
    array_push($item,$newdata);
}
print_r($array1);
youssef hrizi
  • 303
  • 1
  • 3
  • 13

2 Answers2

3

You need to be able to update the original array in the correct way. Firstly to update the original data (in this way) use &$item. Secondly add the item with the correct key rather than use just using array_push() - array_push() will add it with a key of 0 (in this case)...

foreach ($array1 as &$item ){
    $item['newData'] = $newdata;
}

gives the output...

Array
(
    [0] => Array
        (
            [id] => 7
            [code] => 4444
            [newData] => 1111
        )

    [1] => Array
        (
            [id] => 8
            [code] => 3333
            [newData] => 1111
        )

)

Or using the original array and fetching the key in the foreach...

foreach ($array1 as $key => $item ){
    $array1[$key]["newData"] = $newdata;
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
1

I don't think you need to use push. When for loop we need to use & symbol before $ to reference item variable

$array1= array(array('id'=>7,'code'=>4444),array('id'=>8,'code'=>3333));
$newdata = 1111;
foreach ($array1 as &$item ){
    $item["newData"] = $newdata;
}
print_r($array1);

Just do it this way.

William Gunawan
  • 748
  • 3
  • 8