2011-12-05 28 views
1

我試圖把輸入(下面)到多個數組(或可能更簡單到一個數組),最後導出到mysql表中,輸入數據如下:PHP格式輸入數據,並把它放到多個陣列

0 98 
77 09 
0 12 
0 98234 

32 0 
0 1 
0 0 
345 32 

34 9 
6437 34 
789 0 
0 0 

. 
. 

34 0 

我簡單的代碼($ run_txt_filter1輸入):

if ($counted == 64) 
{ 
    echo "line's number: ".$counted; 
    //echo $run_txt_filter1; 
    for ($modi = 0; $modi <= 15; $modi++) 
    { 
     for ($simhi = 1; $simhi <= 4 ; $simhi++) 
     { 
       $exploded=explode(" ", $run_txt_filter1); 
       var_dump($exploded)." \n"; 
     } 

    } 

} 

爲什麼的var_dump口口聲聲說從0-64的ID? (總是應該有64條輸入線)。 什麼是真正想實現的是:

array0=(0, 77, 0, 0) 
array1=(98, 09, 12, 98234) 
array2=(32, 0, 0, 345) 
. 
. 
array30=(0, 12, 0, 34) 
array31=(0, 0, 0, 0) 

在此先感謝

+0

$ count的值設置在哪裏? – Biotox

+0

$ count只用於檢查$ run_txt_filter1是否有64行數據。它是在'if'控制之前設置的 –

+0

爲什麼不能用逗號而不是空格分開?然後將它分解爲1個數組而不是多個數組(這會更容易和更簡單地進行操作,我想你只是將所有那些數據導出到你的數據庫)就像你想要發生的事情一樣? –

回答

1

嘗試分開你的爆炸下一行和爆炸的空白。導致上面的代碼讀取整個字符串,導致程序將其存儲在單個陣列上。因此到那時它將是一個嵌套循環。 :)

0

考慮此輸入:

$in = <<<IN 
0 98 
77 09 
0 12 
0 98234 

32 0 
0 1 
0 0 
345 32 

34 9 
6437 34 
789 0 
0 0 
IN; 

該算法解決您的問題,我認爲:

$final_array = array(); 
$offset = 0; 
foreach(preg_split("/(\r?\n){2,}/",$in) as $block){ 
    foreach(preg_split("/(\r?\n)/",$block) as $line){ 
     foreach(preg_split("/\s+/",$line) as $column => $value){ 
      if($value=='') continue; 
      if(!isset($final_array[$offset+$column])) 
       $final_array[$offset+$column] = array(); 
      $final_array[$offset+$column][]=$value; 
     } 
    } 
    $offset = count($final_array); 
} 
print_r($final_array); 
0

嘗試類似這樣的一個我不知道的東西,如果這會工作:

輸入:

$inputs = "0 98 
77 09 
0 12 
0 98234 

32 0 
0 1 
0 0 
345 32 

34 9 
6437 34 
789 0 
0 0 

. 
. 

34 0"; 

代碼:

$run_txt_filter1 = explode("\n", $inputs); 

if(count($run_txt_filter1) == 64) 
{ 
foreach($run_txt_filter1 as $input) 
{ 
    $exploded = explode(' ', $input); 
    print_r($exploded); 
} 
} 

的「\ n」是針對Windows的下一行,但它是在Linux上的「\ R」不同,我不知道這是否會工作,你也可以嘗試組合

explode("\r\n", $inputs); 

但只是一個嘗試,如果下一行將不起作用我認爲你可以用一些其他方式來分隔每一組值的用戶其他類型的字符,如',',';',':'等。:)

相關問題