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条回答
闹够了就滚
2楼-- · 2020-02-07 19:46
$new_input = array('type' => 'text', 'label' => 'First name', 'show' => true, 'required' => true);
$options['inputs']['name'] = $new_input;
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-07 19:48

Instead of array_push(), use array_merge()

It will merge two arrays and combine their items in a single array.

Example Code -

$existing_array = array('a'=>'b', 'b'=>'c');
$new_array = array('d'=>'e', 'f'=>'g');

$final_array=array_merge($existing_array, $new_array);

Its returns the resulting array in the final_array. And results of resulting array will be -

array('a'=>'b', 'b'=>'c','d'=>'e', 'f'=>'g')

Please review this link, to be aware of possible problems.

查看更多
smile是对你的礼貌
4楼-- · 2020-02-07 19:56

You can try.

$options['inputs'] = $options['inputs'] + $new_input;
查看更多
够拽才男人
5楼-- · 2020-02-07 19:56

First of all, you need to define an array

 $myArray= array();

Then you can push anything to your array, here I try with an associative array

    array_push( $myArray ,array('id'=>23, 'category'=>'aaa'));

You can see the changed array in php:

print_r($myArray);

Result: Array ( [0] => Array ( [id] => 23 [category] => aaa ) )

查看更多
来,给爷笑一个
6楼-- · 2020-02-07 19:57

WebbieDave's solution will work. If you don't want to overwrite anything that might already be at 'name', you can also do something like this:

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

查看更多
来,给爷笑一个
7楼-- · 2020-02-07 19:58

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

查看更多
登录 后发表回答