有条件地将关联元素添加到数组
如何有条件地添加 'b' =>; 'xyz'
在下面的数组中,在 array() 语句中?
$arr = array('a' => abc)
三元运算符不允许我这样做。
How can I conditionally add 'b' => 'xyz'
in the array below, in the array() statement?
$arr = array('a' => abc)
The ternary operator doesn't let me do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
在 PHP 8.1 中,您可以通过数组解包来完成此操作:
请参阅 https://php.watch/versions/8.1/spread-operator-string-array-keys
In PHP 8.1 you can do this with array unpacking:
See https://php.watch/versions/8.1/spread-operator-string-array-keys
这是一个老问题,但您可以使用 array_merge 来完成此操作:
This is an old question, but you can accomplish this with array_merge:
您需要两个步骤:
You need two steps:
如果您确实想使用三元运算符:
If you really want to use the ternary operator:
不确定你在问什么;为什么不呢
Not sure what you're asking; why not
三元的意思是三个项。你必须有一个条件,一个真实的部分,一个虚假的部分。它取代了 if 条件 then true 部分 else false 部分。你不能省略第三部分。 5.3 中有一个快捷方式,如果条件也可以用作真实部分,但它仍然有三个术语,则允许您省略真实部分。
Ternary means three terms. You must have a condition, a true part, and a false part. It takes the place of if condition then true part else false part. You can't leave out the third part. There is a shortcut in 5.3 that allows you to leave out the true part if the condition can be used also as the true part but it still really has three terms.
array_merge()
、array_replace()
、“数组联合运算符”和数组解包都是将关联元素添加到关联数组的潜在合适工具。请注意,如果关联数组具有数字键,则在将数组连接在一起时可能存在覆盖元素的风险。
下面演示了上述技术,以及它们如何根据原始数组的顺序和考虑到键冲突的影响有条件添加的元素影响输出。 演示
输入:
array_merge()
,array_replace()
, the "array union operator", and array unpacking are all potentially suitable tools to add associative elements to an associative array.Note that if your associative array has numeric keys, there may be a risk of overwriting elements while joining the arrays together.
Here's a demonstration of the aforementioned techniques and how they affect the output based on the order of the original array and the conditionally added element(s) considering the impact of key collisions. Demo
Inputs: