dongxia2030 2015-02-08 11:18
浏览 68
已采纳

从长字符串中分解出多维数组

I have a string:

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

Every line is of course ending with a , and every text bit is separated with a \t. This is something I cannot change.

i.e. Some text1\tInfo about text1\tNumbers about text1

The string comes via a $_POST() and I then want to explode this so that i can save each part of each line in my DB.

My code:

$sigs = $_POST['allSigInput'];

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

var_dump($strings);

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

This explodes the string just fine but var_dump(); for all $sigArr_# are the same, and the last array saved.

So all 3 outputs are the same:

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

I would of course like the 3 arrays to contain info respectively to each line of text and be exploded so every bit of text separated by \t, is in an array.

  • 写回答

1条回答 默认 最新

  • douyuan3842 2015-02-08 11:35
    关注

    I'm not sure how you wish to store the data but I think you have an extra loop here.

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

    Eighter use foreach or for in order the loop through strings array.

    And your test condition in for loop is wrong

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

    should be

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

    Say you wish to use the for loop, then your code becomes

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

    Then you can see the output correcty with

    var_dump($sigArr_0);
    var_dump($sigArr_1);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 nrf52810-c三个a 程序
  • ¥15 lego-loam跑出来的roll误差很大
  • ¥50 求一个半透明没有锯齿的圆角窗体的实现例子
  • ¥15 STM32cubeMX里的FreeRTOS无法释放内存
  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对