i am trying to push multiple arrays into 1 big array, resulting in a 2 lvl array.
I got this set of arrays for example:
Array ( [cod] => ddd [denum] => ffffffffffffffff [descr] => ggggggg [cant] => 3 ) Array ( [cod] => fff [denum] => dfgdfgdfgdfgdfg [descr] => dfgdfgdfgdfgdfg [cant] => 33 )
But, after array push, i get this array:
Array ( [0] => Array ( [0] => ddd [1] => ffffffffffffffff [2] => ggggggg [3] => 3 ) [1] => Array ( [0] => fff [1] => dfgdfgdfgdfgdfg [2] => dfgdfgdfgdfgdfg [3] => 33 ) )
Basically this is what i want to do, BUT, if you notice after the push, the keys are forgotten, and converted to numeric.
This is what i want it to look like:
Array ( [0] => Array ( [cod] => ddd [denum] => ffffffffffffffff [descr] => ggggggg [cant] => 3 ) [1] => Array ( [cod] => fff [denum] => dfgdfgdfgdfgdfg [descr] => dfgdfgdfgdfgdfg [cant] => 33 ) )
sample code im using:
$res_arr_values = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { array_push($res_arr_values, array_values($row)); }
Can someone help me with it ?
Adding array into an array in PHP To add an array into an array in PHP, use the array_push() function. The array_push() function takes an array as an argument and returns the array combining with old and new values.
Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.
To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object.
Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).
Don't use array_values
on your $row
$res_arr_values = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { array_push($res_arr_values, $row); }
Also, the preferred way to add a value to an array is writing $array[] = $value;
, not using array_push
$res_arr_values = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $res_arr_values[] = $row; }
And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC)
but to use mysql_fetch_assoc($result)
directly.
$res_arr_values = array(); while ($row = mysql_fetch_assoc($result)) { $res_arr_values[] = $row; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With