2013-04-25 158 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; 
}