0

问题

目前我的输出是这样的PNL 测试 1,10,PNL 测试 2,55,我想操纵它并将它存储在两个不同的变量中作为字符串,如:

$teams = "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;
}
4

3 回答 3

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]);
于 2013-04-25T15:41:39.553 回答
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"
于 2013-04-25T15:39:36.787 回答
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;
}
于 2013-04-25T16:07:34.580 回答