【问题标题】:Exploded multidimensional array from long string从长字符串分解的多维数组
【发布时间】:2015-04-08 05:17:59
【问题描述】:

我有一个字符串:

Some text1    Info about text1     Numbers about text1  
Some text2    Info about text2     Numbers about text2  
Some text3    Info about text3     Numbers about text3

当然,每一行都以\n 结尾,每个文本位都以\t 分隔。这是我无法改变的。

即一些 text1\tInfo about text1\tNumbers about text1\n

字符串来自 $_POST(),然后我想分解它,以便我可以将每一行的每一部分保存在我的数据库中。

我的代码:

$sigs = $_POST['allSigInput'];

$strings = explode ("\n", $sigs);
$sigCount = count($strings);

var_dump($strings);

foreach($strings as $string) {
    for($c=0; $c<=$sigCount; $c++) {
        ${'sigArr_'.$c} = explode ("\t", $string);
    }
}

这会很好地爆炸字符串但是 var_dump();对于所有 $sigArr_# 都是相同的,并且保存了最后一个数组。

所以所有 3 个输出都是相同的:

array (size=3)
  0 => string 'Some Text3'
  1 => string 'Info about text3'
  2 => string 'Numbers about text3'

我当然希望这 3 个数组分别包含每一行文本的信息并被分解,以便由 \t 分隔的每一位文本都在一个数组中。

【问题讨论】:

    标签: php arrays string multidimensional-array explode


    【解决方案1】:

    我不确定您希望如何存储数据,但我认为您在这里有一个额外的循环。

    foreach($strings as $string) {
        for($c=0; $c<=$sigCount; $c++) {
            ${'sigArr_'.$c} = explode ("\t", $string);
        }
    }
    

    Eighter 使用foreachfor 来循环遍历strings 数组。

    你在for循环中的测试条件是错误的

    for($c=0; $c<=$sigCount; $c++)
    

    应该是

    for($c=0; $c<$sigCount; $c++)
    

    假设你想使用for循环,那么你的代码就变成了

    //foreach($strings as $string) {
        for($c=0; $c<$sigCount; $c++) {
            ${'sigArr_'.$c} = explode ("\t", $strings[$c]);
        }
    //}
    

    然后你可以看到输出正确

    var_dump($sigArr_0);
    var_dump($sigArr_1);
    

    【讨论】:

    • 善良的互联网先生。你让我今天很开心!非常感谢!!我不能投票,因为我还没有 15 名声望,但我稍后会这样做!我现在是一个大大的笑容!谢谢!
    • 不客气:]如果您认为答案正确,您可以接受答案(将不胜感激:])
    猜你喜欢
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 2019-01-17
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多