有条件地将关联元素添加到数组

发布于 2024-11-17 06:56:53 字数 138 浏览 2 评论 0原文

如何有条件地添加 '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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

那请放手 2024-11-24 06:56:53

PHP 8.1 中,您可以通过数组解包来完成此操作:

$arr = [
    'foo' => 'bar', 
    ...($condition ? ['baz' => 'boo' ] : []),
];

请参阅 https://php.watch/versions/8.1/spread-operator-string-array-keys

In PHP 8.1 you can do this with array unpacking:

$arr = [
    'foo' => 'bar', 
    ...($condition ? ['baz' => 'boo' ] : []),
];

See https://php.watch/versions/8.1/spread-operator-string-array-keys

两人的回忆 2024-11-24 06:56:53
$a = array('a' => 'abc') + ($condition ? array('b' => 'xyz') : array());
$a = array('a' => 'abc') + ($condition ? array('b' => 'xyz') : array());
在你怀里撒娇 2024-11-24 06:56:53

这是一个老问题,但您可以使用 array_merge 来完成此操作:

array_merge(['foo' => 'bar'], $condition ? ['baz' => 'boo' ] : []);

This is an old question, but you can accomplish this with array_merge:

array_merge(['foo' => 'bar'], $condition ? ['baz' => 'boo' ] : []);
謌踐踏愛綪 2024-11-24 06:56:53

您需要两个步骤:

$arr = array('a' => 'abc');

if(condition) {
    $arr['b'] = 'xyz';
}

You need two steps:

$arr = array('a' => 'abc');

if(condition) {
    $arr['b'] = 'xyz';
}
满身野味 2024-11-24 06:56:53
$arr = array('a' => 'abc');
if ($condition_required_for_b_to_be_put_in_the_array) {
   $arr['b'] = 'xyz';
}

如果您确实想使用三元运算符:

$arr = array('a' => 'abc', $condition ? 'b' : '' => $condition ? 'xyz' : '');
$arr = array_filter($arr);
$arr = array('a' => 'abc');
if ($condition_required_for_b_to_be_put_in_the_array) {
   $arr['b'] = 'xyz';
}

If you really want to use the ternary operator:

$arr = array('a' => 'abc', $condition ? 'b' : '' => $condition ? 'xyz' : '');
$arr = array_filter($arr);
风吹雨成花 2024-11-24 06:56:53

不确定你在问什么;为什么不呢

if (condition) { 
   $arr['b'] = 'xyz';
}

Not sure what you're asking; why not

if (condition) { 
   $arr['b'] = 'xyz';
}
瑕疵 2024-11-24 06:56:53

三元的意思是三个项。你必须有一个条件,一个真实的部分,一个虚假的部分。它取代了 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.

从此见与不见 2024-11-24 06:56:53

array_merge()array_replace()、“数组联合运算符”和数组解包都是将关联元素添加到关联数组的潜在合适工具。

请注意,如果关联数组具有数字键,则在将数组连接在一起时可能存在覆盖元素的风险。

下面演示了上述技术,以及它们如何根据原始数组的顺序和考虑到键冲突的影响有条件添加的元素影响输出。 演示

输入:

$arr = ['a' => 'abc'];
$add = ['b' => 'bar', 'a' => 'foo'];

echo json_encode(array_merge($arr, count($add) > 1 ? $add : []));
// {"a":"foo","b":"bar"}

echo json_encode(array_replace($arr, count($add) > 1 ? $add : []));
// {"a":"foo","b":"bar"}

echo "\n---\n";

echo json_encode($arr + (count($add) > 1 ? $add : []));
// {"a":"abc","b":"bar"}    

echo json_encode((count($add) > 1 ? $add : []) + $arr);
// {"b":"bar","a":"foo"}    

echo json_encode([...$arr, ...count($add) > 1 ? $add : []]);
// {"a":"foo","b":"bar"}

echo json_encode([...count($add) > 1 ? $add : [], ...$arr]);
// {"b":"bar","a":"abc"}

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:

$arr = ['a' => 'abc'];
$add = ['b' => 'bar', 'a' => 'foo'];

echo json_encode(array_merge($arr, count($add) > 1 ? $add : []));
// {"a":"foo","b":"bar"}

echo json_encode(array_replace($arr, count($add) > 1 ? $add : []));
// {"a":"foo","b":"bar"}

echo "\n---\n";

echo json_encode($arr + (count($add) > 1 ? $add : []));
// {"a":"abc","b":"bar"}    

echo json_encode((count($add) > 1 ? $add : []) + $arr);
// {"b":"bar","a":"foo"}    

echo json_encode([...$arr, ...count($add) > 1 ? $add : []]);
// {"a":"foo","b":"bar"}

echo json_encode([...count($add) > 1 ? $add : [], ...$arr]);
// {"b":"bar","a":"abc"}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文