PHP 创建键和值相同的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5360280/
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
PHP create array where key and value is same
提问by Ozzy
I am using the range()
function to create an array. However, I want the keys
to be the same as the value
. This is ok when i do range(0, 10)
as the index starts from 0
, however if i do range(1, 11)
, the index will still start from 0
, so it ends up 0=>1
when i want it to be 1=>1
我正在使用该range()
函数创建一个数组。但是,我希望keys
与value
. 当我range(0, 10)
从索引开始时这样做是可以的0
,但是如果我这样做range(1, 11)
,索引仍将从中开始0
,所以它0=>1
在我想要的时候结束1=>1
How can I use range()
to create an array where the key
is the same as the value
?
如何range()
创建一个key
与 相同的数组value
?
回答by Mason
回答by Smolla
Or you did it this way:
或者你是这样做的:
$b = array_slice(range(0,10), 1, NULL, TRUE);
Find the output here: http://codepad.org/gx9QH7ES
在这里找到输出:http: //codepad.org/gx9QH7ES
回答by Wallace Maxters
Create a function to make this:
创建一个函数来做到这一点:
if (! function_exists('sequence_equal'))
{
function sequence_equal($low, $hight, $step = 1)
{
return array_combine($range = range($low, $hight, $step), $range);
}
}
Using:
使用:
print_r(sequence_equal(1, 10, 2));
Output:
输出:
array (
1 => 1,
3 => 3,
5 => 5,
7 => 7,
9 => 9,
)
In PHP 5.5 >= you can use Generator to make this:
在 PHP 5.5 >= 中,您可以使用 Generator 来实现:
function sequence_equal($low, $hight, $step = 1)
{
for ($i = $low; $i < $hight; $i += $step) {
yield $i => $i;
}
}
回答by Russell Dias
There is no out of the box solution for this. You will have to create the array yourself, like so:
对此没有开箱即用的解决方案。您必须自己创建数组,如下所示:
$temp = array();
foreach(range(1, 11) as $n) {
$temp[$n] = $n;
}
But, more importantly, whydo you need this? You can just use the value itself?
但是,更重要的是,你为什么需要这个?您可以只使用值本身吗?
回答by Mike Lewis
<?php
function createArray($start, $end){
$arr = array();
foreach(range($start, $end) as $number){
$arr[$number] = $number;
}
return $arr;
}
print_r(createArray(1, 10));
?>
See output here: http://codepad.org/Z4lFSyMy
在此处查看输出:http: //codepad.org/Z4lFSyMy
回答by RDL
<?php
$array = array();
foreach (range(1,11) as $r)
$array[$r] = $r;
print_r($array);
?>