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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?