开发者

converting string to array

I have one question. I created a variable wh开发者_运维问答ich contains the concatenated variable, e.g something like this:

$a=89111213

I want to obtain an array like this:

$b(
  1=>8,
  2=>9,
  3=>11,
  4=>12,
  5=>13
)


Update:

As @therefromhere suggests in his comment, instead of concatenating the numbers into one string,put them in an array directly:

$a = array();

for(...) {
    $a[] = $somevariable;

}

Here is something that works in a way.

Important:
Assumption: Numbers are concatenated in increasing order and start with a number < 10 :)

$str = "89111213";
$numbers = array();
$last = 0;
$n = '';
for($i = 0, $l = strlen($str);$i<$l;$i++) {
    $n .= $str[$i];
    if($n > $last || ($i == $l - 1)) {
        $numbers[] = (int) $n;
        $last = $n;
        $n = '';
    }
}

print_r($numbers);

prints

Array
(
    [0] => 8
    [1] => 9
    [2] => 11
    [3] => 12
    [4] => 13
)

Although this might work to some extend, it will fail in a lot of cases. Therefore:

How do you obtain 89111213 ? If you are generating it from the numbers 8,9,11, etc. you should generate something like 8,9,11,12,13.


You can use explode():

$b = explode(' ', $a);


This looks dangerous. Have you concatenated several numbers to one integer? Note that there's an upper limit on integer values so you may experience bugs with many elements.

Also note that your problem is not possible to solve correctly when the numbers have different lengths, because you cannot know which of these combinations (if any) is correct for 89111213:

  • 8, 9, 11, 12, 13
  • 89, 111, 213
  • 8, 9, 11, 1213
  • 8, 91, 11213

You will need some sort of separator to make it stable and future proof.


<? explode(" ", "a b c d e") ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜