php - push array into array - key issue

后端 未结 6 1708
春和景丽
春和景丽 2021-02-02 10:19

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] => ffffd
    [denum] =         


        
相关标签:
6条回答
  • 2021-02-02 11:04
    $res_arr_values = array();
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
        $res_arr_values[] = $row;
    }
    
    
    array_push == $res_arr_values[] = $row;
    
    example 
    
    <?php
    $stack = array("orange", "banana");
    array_push($stack, "apple", "raspberry");
    print_r($stack);
    
    Array
    (
        [0] => orange
        [1] => banana
        [2] => apple
        [3] => raspberry
    )
    ?>
    
    0 讨论(0)
  • 2021-02-02 11:08

    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;
       }
    
    0 讨论(0)
  • 2021-02-02 11:08

    I think you have to go for

    $arrayname[indexname] = $value;
    
    0 讨论(0)
  • 2021-02-02 11:09

    Use this..

    $res_arr_values = array();
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
        $res_arr_values[] = $row;
    }
    
    0 讨论(0)
  • 2021-02-02 11:13

    first convert your array too JSON

    while($query->fetch()){
       $col[] = json_encode($row,JSON_UNESCAPED_UNICODE);
    }
    

    then vonvert back it to array

    foreach($col as &$array){
       $array = json_decode($array,true);
    }
    

    good luck

    0 讨论(0)
  • 2021-02-02 11:17

    All these answers are nice however when thinking about it....
    Sometimes the most simple approach without sophistication will do the trick quicker and with no special functions.

    We first set the arrays:

    $arr1 = Array(
    "cod" => ffffd,
    "denum" => ffffffffffffffff,
    "descr" => ggggggg,
    "cant" => 3
    );
    $arr2 = Array
    (
    "cod" => fff,
    "denum" => dfgdfgdfgdfgdfg,
    "descr" => dfgdfgdfgdfgdfg,
    "cant" => 33
    );
    

    Then we add them to the new array :

    $newArr[] = $arr1;
    $newArr[] = $arr2;
    

    Now lets see our new array with all the keys:

    print_r($newArr);
    

    There's no need for sql or special functions to build a new multi-dimensional array.... don't use a tank to get to where you can walk.

    0 讨论(0)
提交回复
热议问题