简体   繁体   English

迭代数字范围以添加为键

[英]iterate through range of numbers to add as keys

I have a range of 67 numbers, something like 256 through to 323, which I want to add to an existing array. 我有67个数字的范围,类似于256到323,我想添加到现有数组。 it doesn't matter what the values are. 价值是什么并不重要。

looking for code to iterate through those numbers to add them as keys to the array without adding each one at a time 寻找代码来迭代这些数字,将它们作为键添加到数组中,而不是一次添加每个数字

Try array_fill_keys and range 尝试array_fill_keys范围

$existingArray =  array('foo', 'bar', 'baz');
$existingArray += array_fill_keys(range(256,323), null);

Use whatever you like instead of null . 使用你喜欢的任何东西而不是null You could also use array_flip() instead of array_fill_keys(). 您也可以使用array_flip()而不是array_fill_keys()。 You'd get the index keys as values then, eg 256 => 1, 257 => 2, etc. 您可以将索引键作为值,例如256 => 1,257 => 2等。

Alternatively, use array_merge instead of the + operator. 或者,使用array_merge而不是+运算符。 Depends on the outcome you want . 取决于你想要的结果

你可以使用range()例如range(256,323)

You can try using the range and array_merge functions. 您可以尝试使用rangearray_merge函数。

Something like: 就像是:

<?php

$arr = array(1,2,3); // existing array.
$new_ele = range(256,323); 

// add the new elements to the array.
$arr= array_merge($arr,$new_ele); 

var_dump($arr);

?>

push(); 推(); could be a look worth, or you can do it like this 可能看起来值得,或者你可以这样做

for($i=0;$i<count($array);$i++)
{
$anotherArray[$i] = $array[$i];

}

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

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