PHP将数组中的偶数和奇数值分开

时间:2013-04-26 08:29:44

标签: php regex arrays preg-match

我正在使用下面的代码来分隔奇数和偶数,并将其存储在不同的变量中。当只有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;

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

答案 2 :(得分: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];
}

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