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

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

PHP create array where key and value is same

phparraysrange

提问by Ozzy

I am using the range()function to create an array. However, I want the keysto 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=>1when i want it to be 1=>1

我正在使用该range()函数创建一个数组。但是,我希望keysvalue. 当我range(0, 10)从索引开始时这样做是可以的0,但是如果我这样做range(1, 11),索引仍将从中开始0,所以它0=>1在我想要的时候结束1=>1

How can I use range()to create an array where the keyis the same as the value?

如何range()创建一个key与 相同的数组value

回答by Mason

How about array_combine?

array_combine怎么

$b = array_combine(range(1,10), range(1,10));

回答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);

?>