PHP:将数组中的所有值设置为某物

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11158607/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:52:35  来源:igfitidea点击:

PHP: set all values in an array to something

phparrays

提问by Martin

Hi want to ask if there is a way to do this without foreach ($array as $k=>$v). I know it will work but I'm looking for a more elegant way if you know. So my array was like:

你好想问一下是否有办法在没有 foreach ($array as $k=>$v) 的情况下做到这一点。我知道它会起作用,但如果你知道,我正在寻找一种更优雅的方式。所以我的数组是这样的:

1 = 231
2 = 432
3 = 324

I flipped it and it became: 231 => 1, 432 =>2, 324 => 3. Now what I need to do is to set all values to '1'

我翻转它,它变成了:231 => 1, 432 =>2, 324 => 3。现在我需要做的是将所有值设置为'1'

回答by Rocket Hazmat

You can use array_fill_keys:

您可以使用array_fill_keys

$array = array(
    1 => 231,
    2 => 432,
    3 => 324
);

$array = array_flip($array);

$array = array_fill_keys(array_keys($array), 1);

回答by acme

array_fill_keys()should be what you need:

array_fill_keys()应该是你需要的:

$keys = array_keys($yourArray);
$filled = array_fill_keys($keys, 1);

回答by MortalViews

For PHP >5.3you can use anonymous functions.

对于PHP > 5.3,您可以使用匿名函数。

array_walk($array,function(&$value){$value=1;});

array_walk($array,function(&$value){$value=1;});

Note: value is passed by reference.

注意:值是通过引用传递的。

回答by Xunnamius

I believe you're looking for this function: array_fill()

我相信你正在寻找这个函数:array_fill()

From the above link:

从上面的链接:

"Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter."

“用 value 参数值的 num 个条目填充数组,键从 start_index 参数开始。”

Although if your indices are not numerical and/or are not enumerable (say, from 231 to 324 inclusive), then you may be better off with, as Rocket says, array_fill_keys()or your regular foreach.

尽管如果您的索引不是数字和/或不可枚举(例如,从 231 到 324 包括在内),那么正如 Rocket 所说,使用array_fill_keys()或您的常规 foreach可能会更好。

回答by Pere Hernández

I got at this post with the same question but I ended up getting another aproach.

我在这篇文章中提出了同样的问题,但我最终得到了另一种方法。

Why using array_flip + array_keys instead of simply use array_values?

为什么使用 array_flip + array_keys 而不是简单地使用 array_values?

$array = array(
    1 => 231,
    2 => 432,
    3 => 324
);

$array = array_fill_keys(array_values($array), 1);

回答by user2573099

array_replace(array_flip($columns), array_fill_keys($columns, 0));

回答by Scotch

Any method that you call, such as array_map or fill_keys would still be using a loop to iterate over the array. It seems like you would want something such as array_map, which can be found here

您调用的任何方法(例如 array_map 或 fill_keys)仍将使用循环来迭代数组。似乎您想要诸如array_map之类的东西,可以在这里找到

If you consider that to be more elegant, to each his own:)

如果你认为这样更优雅,每个人都有自己的:)