Push item to associative array in PHP

2020-02-07 19:12发布

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

$new_input['name'] = array(
    'type' => 'text', 
    'label' => 'First name', 
    'show' => true, 
    'required' => true
);
array_push($options['inputs'], $new_input);

However, instead of 'name' as the key in adds a number. Is there another way to do it?

标签: php arrays
13条回答
Rolldiameter
2楼-- · 2020-02-07 20:00
$options['inputs']['name'] = $new_input['name'];
查看更多
Evening l夕情丶
3楼-- · 2020-02-07 20:00

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 )
查看更多
Animai°情兽
4楼-- · 2020-02-07 20:03

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);
查看更多
够拽才男人
5楼-- · 2020-02-07 20:03

Just change few snippet(use array_merge function):-

  $options['inputs']=array_merge($options['inputs'], $new_input);
查看更多
家丑人穷心不美
6楼-- · 2020-02-07 20:07

i use php5.6

code:

$person = ["name"=>"mohammed", "age"=>30];

$person['addr'] = "Sudan";

print_r($person) 

output

Array( ["name"=>"mohammed", "age"=>30, "addr"=>"Sudan"] )
查看更多
Evening l夕情丶
7楼-- · 2020-02-07 20:12

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!

查看更多
登录 后发表回答