php explode and force array keys to start from 1 and not 0

本秂侑毒 提交于 2019-12-08 08:52:44

问题


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.


回答1:


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

Done!




回答2:


Just use a separator to create a dummy element in the head of the array and get rid of it afterwards. It should be the most efficient way to do the job:

function explode_from_1($separator, $string) {
    $x = explode($separator, $separator.$string);
    unset($x[0]);
    return $x;
}

a more generic approach:

function explode_from_x($separator, $string, $offset=1) {
    $x = explode($separator, str_repeat($separator, $offset).$string);
    return array_slice($x,$offset,null,true);
}



回答3:


$somearray = explode(",",$somestring);

foreach($somearray as $key=>$value)
{
   $otherarray[$key+1] = $value;
}

well its dirty but isn't that what php is for...




回答4:


Nate almost had it, but needed a temporary variable:

$someArray = explode(",",$myString);
$tempArray = array();

foreach($someArray as $key=>$value) {
   $tempArray[$key+1] = $value;
}
$someArray = $tempArray;

codepad example




回答5:


$array = array('a', 'b', 'c', 'd');

$flip = array_flip($array);
foreach($flip as &$element) {
    $element++;
}
$normal = array_flip($flip);
print_r($normal);

Try this, a rather funky solution :P

EDIT: Use this instead.

$array = array('a', 'b', 'b', 'd');
$new_array = array();

$keys = array_keys($array);
for($i=0; $i<count($array); $i++) {
    $new_array[$i+1] = $array[$i];
}
print_r($new_array);


来源:https://stackoverflow.com/questions/13148506/php-explode-and-force-array-keys-to-start-from-1-and-not-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!