php 使用关联数组推送数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6618150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array push with associate array
提问by grep
If I am working with an associate array like such:
如果我正在使用这样的关联数组:
Array ( [Username] => user
[Email] => email
)
and I want to add an element to the end, I would think to do:
我想在最后添加一个元素,我想这样做:
array_push($array, array('Password' => 'pass'));
However, this leaves me with:
然而,这给我留下了:
Array ( [Username] => user
[Email] => email
Array ( [Password] => pass )
)
How can this be avoided so I end up with:
如何避免这种情况,所以我最终得到:
Array ( [Username] => user
[Email] => email
[Password] => pass
)
Much appreciated!
非常感激!
回答by Paul.s
You are using an associative array so you just set the key/value pair like this.
您正在使用关联数组,因此您只需像这样设置键/值对。
$array["Password"] = pass;
I think you may need to review the difference between an array and an associative array. For example if I ran the same command again with a different value it would overwrite the old one:
我认为您可能需要查看数组和关联数组之间的区别。例如,如果我使用不同的值再次运行相同的命令,它将覆盖旧的:
$array["Password"] = "overwritten";
Giving you this
给你这个
Array ( [Username] => user
[Email] => email
[Password] => "overwritten"
)
Which judging by your question is not what your expecting
从你的问题来看,这不是你的期望
回答by brianreavis
Try out array_mergeinstead:
改为尝试array_merge:
$array = array('Username' => 'user', 'Email' => 'email');
$array = array_merge($array, array('Password' => 'pass'));
This produces the array:
这将产生数组:
array('Username' => 'user', 'Email' => 'email', 'Password' => 'pass');
回答by Byron Whitlock
Generally, with an associative array you don't have control over the order of the elements.
通常,对于关联数组,您无法控制元素的顺序。
The elements can be in any order.
元素可以按任何顺序排列。
However I've found php keeps the order that you add them.
但是我发现 php 会保留您添加它们的顺序。
So just do $myarra["name"] = "password"
所以就做 $myarra["name"] = "password"
回答by Michael Mior
Associative arrays aren't designed to have their keys in order. You can add an element via
关联数组的设计并不是为了按顺序排列它们的键。您可以通过添加元素
$array['Password'] = 'pass';