pushing objects into existing array with php
10,245
Solution 1
check this: array_push
you could do:
$array = [];
array_push($array, "item");
or
$array = [];
$item = "hi";
$array['key'] = $item;
or you could use
$array = [];
array_merge($array, ["abc" => 1]);
also your js code is equivilant to
$array = [];
array_push($array, ['item' => 'value', 'item1' => 'value1']);
// is equivalent to
var arr = [];
arr.push({
sku : foo,
quantity: bar
});
Solution 2
This was accomplished by the following:
array_push($someArray, ["sku" => $sku, "quantity" => $quantity]);
Solution 3
No need for an array_push function. See ex:
$arr = [];
$arr['sku'] = $sku;
$arr['quantity'] = $quantity;
when handling key -> value pairs.
Edit (multidimensional one):
for($a=0; $a < $total ; $a++)
{
$arr[$a]['sku'] = $sku;
$arr[$a]['quantity'] = $quantity;
}
Related videos on Youtube
Comments
-
jremi almost 2 years
In JS I would do something like this:
var arr = []; arr.push({ sku : foo, quantity: bar });
How do I do this with PHP? When I try to do this I'm getting a parsing error.
For example with PHP:
$someArray = array(); // or maybe someArray = []; ??? $someArray = array_push( 'sku' => $sku, 'quantity' => $quantity );
Is this correct?
Thank you!
-
Madhawa Priyashantha over 6 years
-
jremi over 6 yearsthx for link, I checked this, but the prob is not with adding 1 value to the existing array. I'm having a trouble with the key/value pairs.
-
Mark Baker over 6 years
$someArray = array_push([ 'sku' => $sku, 'quantity' => $quantity ]);
perhaps? -
Dhaval Chheda over 6 yearsit looks like you are trying to pass an array into an array so you can array_merge() maybe.
-
fungusanthrax over 6 years$arrayName[] = $addItem; is faster than array_push
-
jremi over 6 years@MarkBaker that is what i needed . thx
-
-
jremi over 6 yearsI am looping over data and need to push them into the master array. The method you have described here will overwrite. I need to keep pushing each new sku/quantity into the master array.
-
epipav over 6 yearsThen I can think of two easy options. You can either insert the array to the master array after each iteration, or you can keep the data in a multi-dimensional array. Check my edit.