将没有分隔符的数字字符串转换为可能为多位数字的数组

发布于 2024-10-08 11:45:51 字数 183 浏览 8 评论 0原文

如何将没有分隔符的字符串(例如 $a = '89111213';)拆分为整数数组?

期望的结果:

[8, 9, 11, 12, 13]

我在循环中生成输入数字,并使用 $a .= $somevariable; 之类的串联。

How can I split a string with no delimiters, for example $a = '89111213';, into an array of integers?

Desired result:

[8, 9, 11, 12, 13]

I generate that input number in a loop with concatenation like $a .= $somevariable;.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

只想待在家 2024-10-15 11:45:51

更新:

正如@therefromhere在他的评论中建议的那样,不要将数字连接成一个字符串,而是直接将它们放入一个数组中:

$a = array();

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

}

这是一种在某种程度上有效的方法。

重要:
假设:数字按升序连接,并以数字 开头。 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);

打印

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

虽然这可能在某种程度上有效,但在很多情况下会失败。因此:

如何获得 89111213 ?如果您从数字 8、9、11 等生成它,您应该生成类似 8,9,11,12,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.

人生戏 2024-10-15 11:45:51

您可以使用 explode()

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

You can use explode():

$b = explode(' ', $a);
还在原地等你 2024-10-15 11:45:51

这看起来很危险。您是否将多个数字连接成一个整数?请注意,整数值有上限,因此您可能会遇到许多元素的错误。

另请注意,当数字具有不同长度时,您的问题无法正确解决,因为您无法知道这些组合(如果有)中的哪一个对于 89111213 是正确的:

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

您将需要某种分隔符以使其稳定且面向未来。

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.

流星番茄 2024-10-15 11:45:51
<? explode(" ", "a b c d e") ?>
<? explode(" ", "a b c d e") ?>
落叶缤纷 2024-10-15 11:45:51

这是一个您不需要解决的 XY 问题。首先不要使用串联来构建输入字符串。更改语法以将元素推入平面数组中:

$result = [];
foreach ($somevariables as $somevariable) {
    $result[] = $somevariable;
}
var_export($result);

在您的编码要求合法的另一个宇宙中,我有几个解决方案,它们将努力将字符串拆分为递增值的数组(假设数据适应这种拆分) )。

函数式风格:(演示)

$str = '89111213';

var_export(
    array_reduce(
        str_split($str),
        function ($result, $digit) {
            if (count($result) > 1 && strnatcmp(...array_slice($result, -2)) > 0) {
                $result[array_key_last($result)] .= $digit;
            } else {
                $result[] = $digit;
            }
            return $result;
        },
        []
    )
);

使用引用:(演示)

$str = '89111213';

$result = [];
$last = '';
$secondLast = '';
foreach (str_split($str) as $digit) {
    if (($secondLast <=> $last) === 1) {
        $last .= $digit;
    } else {
        $secondLast =& $last;
        unset($last);
        $last = $digit;
        $result[] =& $last;
    }
}
var_export($result);

This is an XY Problem that you shouldn't need to solve. Simply don't use concatenation to build the input string in the first place. Change your syntax to push elements into a flat array:

$result = [];
foreach ($somevariables as $somevariable) {
    $result[] = $somevariable;
}
var_export($result);

In an alternate universe where your coding requirement is legitimate, I've got a couple of solutions which will endeavor to split the string into an array of increasing values (assuming the data accommodates such splitting).

Functional style: (Demo)

$str = '89111213';

var_export(
    array_reduce(
        str_split($str),
        function ($result, $digit) {
            if (count($result) > 1 && strnatcmp(...array_slice($result, -2)) > 0) {
                $result[array_key_last($result)] .= $digit;
            } else {
                $result[] = $digit;
            }
            return $result;
        },
        []
    )
);

Using references: (Demo)

$str = '89111213';

$result = [];
$last = '';
$secondLast = '';
foreach (str_split($str) as $digit) {
    if (($secondLast <=> $last) === 1) {
        $last .= $digit;
    } else {
        $secondLast =& $last;
        unset($last);
        $last = $digit;
        $result[] =& $last;
    }
}
var_export($result);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文