php - push array into array - key issue

user1248047 picture user1248047 · Mar 4, 2012 · Viewed 174.3k times · Source

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 ?

Answer

Basti picture Basti · Mar 4, 2012

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;
   }