Push item to associative array in PHP

后端 未结 12 1327
野趣味
野趣味 2020-12-04 22:47

I\'ve been trying to push an item to an associative array like this:

$new_input[\'name\'] = array(
    \'type\' => \'text\', 
    \'label\' => \'First          


        
相关标签:
12条回答
  • 2020-12-04 23:32
    $options['inputs']['name'] = $new_input['name'];
    
    0 讨论(0)
  • 2020-12-04 23:32

    Curtis's answer was very close to what I needed, but I changed it up a little.

    Where he used:

    $options['inputs']['name'][] = $new_input['name'];
    

    I used:

    $options[]['inputs']['name'] = $new_input['name'];
    

    Here's my actual code using a query from a DB:

    while($row=mysql_fetch_array($result)){ 
        $dtlg_array[]['dt'] = $row['dt'];
        $dtlg_array[]['lat'] = $row['lat'];
        $dtlg_array[]['lng'] = $row['lng'];
    }
    

    Thanks!

    0 讨论(0)
  • 2020-12-04 23:33

    If $new_input may contain more than just a 'name' element you may want to use array_merge.

    $new_input = array('name'=>array(), 'details'=>array());
    $new_input['name'] = array('type'=>'text', 'label'=>'First name'...);
    $options['inputs'] = array_merge($options['inputs'], $new_input);
    
    0 讨论(0)
  • 2020-12-04 23:37

    Just change few snippet(use array_merge function):-

      $options['inputs']=array_merge($options['inputs'], $new_input);
    
    0 讨论(0)
  • 2020-12-04 23:37

    You can use array_merge($array1, $array2) to merge the associative array. Example:

    $a1=array("red","green");
    $a2=array("blue","yellow");
    print_r(array_merge($a1,$a2));
    

    Output:

    Array ( [0] => red [1] => green [2] => blue [3] => yellow )
    
    0 讨论(0)
  • 2020-12-04 23:38

    This is a cool function

    function array_push_assoc($array, $key, $value){
       $array[$key] = $value;
       return $array;
    }
    

    Just use

    $myarray = array_push_assoc($myarray, 'h', 'hello');
    

    Credits & Explanation

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