PHP将值推入关联数组 [英] PHP push values into associative array
本文介绍了PHP将值推入关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在任何地方都找不到答案.
I can't find an answer to this anywhere.
foreach ($multiarr as $array) {
foreach ($array as $key=>$val) {
$newarray[$key] = $val;
}
}
说 $ key
具有重复的名称,所以当我尝试插入 $ newarray
时,它实际上是这样的:
say $key
has duplicate names, so when I am trying to push into $newarray
it actually looks like this:
$newarray['Fruit'] = 'Apples';
$newarray['Fruit'] = 'Bananas';
$newarray['Fruit'] = 'Oranges';
问题是,上面的示例只是替换旧值,而不是强制使用旧值.
The problem is, the above example just replaces the old value, instead of pushing into it.
是否可以像这样推送值?
Is it possible to push values like this?
推荐答案
是的,请注意新的一对方括号:
Yes, notice the new pair of square brackets:
foreach ($multiarr as $array) {
foreach ($array as $key=>$val) {
$newarray[$key][] = $val;
}
}
您还可以使用 array_push()
,引入一个有点开销,但是我通常会坚持使用速记.
You may also use array_push()
, introducing a bit of overhead, but I'd stick with the shorthand most of the time.
这篇关于PHP将值推入关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文