问题
目前我的输出就像这样 PNL测试1,10,PNL测试2,55,我想操纵它并将其存储在两个不同的变量中,如:
$ teams =" PNL测试1,PNL测试2&#34 ;;
$ amount =" 10,55&#34 ;;
请告诉我如何分割以上格式。
代码
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 :(得分: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"
答案 1 :(得分: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]);
答案 2 :(得分:0)
比RegExp更不像花哨,但更明显:
$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;
}