2013-04-25 71 views
0

問題我應該如何將數組的值分爲偶數,奇數?

目前我的輸出來了這樣PNL測試1,10,PNL測試2.55,我想操縱它,它在兩個不同的變量存儲爲喜歡的字符串:

$車隊 =「PNL測試1,PNL測試2」;

$ amount =「10,55」;

請讓我知道我應該如何拆分上述格式。

代碼

while ($row1 = mysql_fetch_assoc($result)){ 
    $profit = 0; 
    $total = 0; 
    $loss = 0; 
    $final_array = ''; 
    $final_array .= $teams = $row1['t_name'].","; 
    $teams = explode(",", $teams); 

    $transact_money = $row1['pnl_amount']; 
    $pnl_results = $row1['pnl']; 

    $transact_money = explode("|", $transact_money); 
    $pnl_results = explode("|", $pnl_results); 
    for($i=0; $i<count($transact_money); $i++){ 
     if($pnl_results[$i]=='Profit'){ 
      $profit = $profit + $transact_money[$i]; 
     }else{ 
      $loss = $loss + $transact_money[$i]; 
     }//end if 
    }//end for.. 
    $team_profits = $profit - $loss.","; 
    $final_array .= $team_profits; 

    echo $final_array; 
} 
+0

爲什麼不拆出while循環的結果? – 2013-04-25 16:10:47

回答

0
$s = "PNL testing 1,10,PNL testing 2,55"; 
$res = array(); 
$result = preg_match_all("{([\w\s\d]+),(\d+)}", $s, $res); 
$teams = join(', ', $res[1]); //will be "PNL testing 1, PNL testing 2" 
$amount = join(', ', $res[2]); //will be "10, 55" 
+0

感謝您的工作,但當價值從** PNL測試1,10,PNL測試2,25 **增加到** PNL測試1,10,PNL測試2,25,Faltu團隊,99 **仍然只顯示2個值在每個變量中。有反正使$ res動態嗎?此外,變量** $ final_array **存儲值**「PNL測試1,10,PNL測試2,55」**並在while循環內完美顯示。你能指導我做些什麼,以便我可以在while循環外打印出值。 – colourtheweb 2013-04-25 15:54:20

0
$string = "PNL testing 1,10,PNL testing 2,55,"; 
preg_match_all("/(PNL testing \d+),(\d+),/", $string, $result); 
$teams = implode(",", $result[1]); 
$amount = implode(",", $result[2]); 
+0

感謝你的工作,但是當價值從PNL測試增加1,10,PNL測試2,25到PNL測試1,10,PNL測試2,25,Faltu團隊99仍然只顯示每個變量的2個值。有反正使$ res動態嗎?變量$ final_array存儲值「PNL測試1,10,PNL測試2,55」並在while循環內完美顯示。你能指導我做些什麼,以便我可以在while循環外打印出值。 – colourtheweb 2013-04-25 15:58:27

0

少花哨比正則表達式,但更明顯:

$final_array = "PNL testing 1,10,PNL testing 2,55"; 

$final_array_array = explode(',', $final_array); 

$teams = array(); 
$amount = array(); 
$index = 0; 

foreach ($final_array_array as $item) { 
    switch ($index) { 
     case 0: 
      $teams[] = $item; 
      break; 
     case 1: 
      $amount[] = $item; 
    } 
    $index = 1-$index; 
} 
相關問題