php爆炸并强制数组键从1开始而不是0(php explode and force array keys to start from 1 and not 0)

113 IT屋

I have a string that will be exploded to get an array, and as we know, the output array key will start from 0 as the key to the first element, 1 for the 2nd and so on.

Now how to force that array to start from 1 and not 0?

It's very simple for a typed array as we can write it like this:

array('1'=>'value', 'another value', 'and another one');

BUT for an array that is created on the fly using explode, how to do it?

Thanks.

解决方案
$exploded = explode('.', 'a.string.to.explode');
$exploded = array_combine(range(1, count($exploded)), $exploded);
var_dump($exploded);

Done!

我有一个字符串,它将被分解成一个数组,并且我们知道,输出数组键将从0开始作为第一个元素的键,从1开始代表第二个元素,依此类推。



现在如何强制该数组从1开始而不是从0开始?



对于类型化数组,这很简单,因为我们可以这样写像这样:



  array('1'=>'value','another value','and another one' ); 


但是要使用爆炸在运行中创建一个数组,该怎么做?



谢谢。


解决方案
  $爆炸了= explode('。','a.string.to.explode'); 
$ exploded = array_combine(range(1,count($ exploded)),$ exploded);
var_dump($ exploded);


完成!


本文地址:IT屋 » php爆炸并强制数组键从1开始而不是0

相关文章: