简体   繁体   English

PHP创建数组,其中键和值相同

[英]PHP create array where key and value is same

I am using the range() function to create an array. 我使用range()函数来创建一个数组。 However, I want the keys to be the same as the value . 但是,我希望keysvalue相同。 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 当我从0开始执行range(0, 10) 0,10)时这是可以的,但是如果我执行range(1, 11) ,索引仍将从0开始,所以当我想要它时它会结束0=>11=>1

How can I use range() to create an array where the key is the same as the value ? 如何使用range()创建一个数组,其中keyvalue相同?

array_combine怎么

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

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

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;
    }
}

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, why do you need this? 但是,更重要的是,你为什么需要这个呢? You can just use the value itself? 你可以只使用这个值吗?

<?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

<?php

$array = array();
foreach (range(1,11) as $r)
  $array[$r] = $r;

print_r($array);

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM