数组函数创建新数组,以值作为键?

时间:2021-12-08 21:15:34

I have an array:

我有一个数组:

$ids = array(1 => '3010', 2 => '10485', 3 => '5291');

I want to create a new array that takes the values of the $ids array and sets them as the keys of a new array, having the same value.

我想创建一个新数组,它接受$ ids数组的值,并将它们设置为具有相同值的新数组的键。

The final array would be:

最后一个数组是:

$final = array('3010' => 'Green', '10485' => 'Green', '5291' => 'Green');

This will be used in apc_add().

这将在apc_add()中使用。

I know I can accomplish this by looping thru it.

我知道我可以通过循环来实现这一目标。

$final = array();

foreach($ids as $key => $value):
  $final[$value] = 'Green';
endforeach;

But I was wondering if there was php function that does this without having to use a forloop, thanks!

但我想知道是否有PHP功能,而不必使用forloop,谢谢!

2 个解决方案

#1


5  

You are looking for array_fill_keys.

您正在寻找array_fill_keys。

$final = array_fill_keys($ids, "Green");

However, be aware that strings that are decimal representations of integers are actually converted to integers when used as array keys. This means that in your example the numbers that end up as keys in $final will have been transformed to integers. Most likely won't make a difference in practice, but you should know about it.

但是,请注意,作为整数的十进制表示的字符串在用作数组键时实际上会转换为整数。这意味着在您的示例中,最终作为$ final中的键的数字将被转换为整数。最有可能在实践中不会有所作为,但你应该知道它。

#2


3  

You can do with array_fill_keys this way:

您可以这样使用array_fill_keys:

$final = array_fill_keys($ids, "Green");

#1


5  

You are looking for array_fill_keys.

您正在寻找array_fill_keys。

$final = array_fill_keys($ids, "Green");

However, be aware that strings that are decimal representations of integers are actually converted to integers when used as array keys. This means that in your example the numbers that end up as keys in $final will have been transformed to integers. Most likely won't make a difference in practice, but you should know about it.

但是,请注意,作为整数的十进制表示的字符串在用作数组键时实际上会转换为整数。这意味着在您的示例中,最终作为$ final中的键的数字将被转换为整数。最有可能在实践中不会有所作为,但你应该知道它。

#2


3  

You can do with array_fill_keys this way:

您可以这样使用array_fill_keys:

$final = array_fill_keys($ids, "Green");