2

我正在使用下面的代码来分隔奇数和偶数并将其存储在不同的变量中。当只有 2 个值可用时,它可以正常工作,但是当数值增加时,它不会。我想让它动态化,以便可以正确分离和存储 n 个值。

示例:如果值为

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

它打印得很好:

$teams = "PNL testing 1, PNL testing 2";

$amount = "10, 35";

但是当它从

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

$final_array = "PNL testing 1,10,PNL testing 2,35,Team 3,95,";

然后它也打印

$teams = "PNL testing 1, PNL testing 2";

$amount = "10, 35"; 

请指导我了解我哪里出错了。

$res = array();
$result = preg_match_all("{([\w\s\d]+),(\d+)}", $final_array, $res);
$teams = join(', ', $res[1]); //will display teams
$amount = join(', ', $res[2]); //will display amount every team have
echo $teams . "<br />" . $amount;
4

3 回答 3

3

我认为您可以完全放弃 REGEX 以支持旧的explode/implode包含一些逻辑:

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

$a = explode(',', trim(trim($final_array), ','));
foreach ($a as $i => $v)
    if (($i % 2) == 0) $teams[] = trim($a);
    else $amount[] = trim($a);

$teams = implode(', ', $teams);
$amount = impode(', ', $amount);

在上面的代码中$tms$amn都是临时数组。在 foreach 中,我们从字符串中获取分解后的值,然后将它们存储在这两个数组中,按键对其进行排序(如果它是一个团队,那么它就是一个数量)。

最后,我们只是将新值内爆到您的输出变量$teams$amount.

于 2013-04-26T08:41:04.037 回答
0

我认为使用起来会容易得多explode

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

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

foreach ($result as $key => $value) {
    if ($key % 2 == 0) {
        $teams[] = $value;
    } else {
        $amount[] = $value;
    }
}

$teams  = implode(', ', $teams); //will display teams
$amount = implode(', ', $amount); //will display amount every team have
echo $teams."<br />".$amount;
于 2013-04-26T08:41:27.623 回答
0

我会更改Michal Trojanowski的这一部分以提高效率

foreach ($result as $key => $value) {
    if ($key % 2 == 0) {
        $teams[] = $value;
    } else {
        $amount[] = $value;
    }
}

你看它有一个额外的条件我们可以像这样删除它

$length = count($result);//cache count result
for ($i = 0; $i < $length; $i += 2) {
    $teams[] = $result[$i];
}

for ($i = 1; $i < $length; $i += 2) {
    $amount[] = $result[$i];
}

这里循环运行相同,但它只是删除了条件。

于 2017-02-27T21:04:46.480 回答