PHP将数组添加到数组中

时间:2014-07-11 12:33:02

标签: php arrays regex loops

我正在尝试在循环时添加到数组,虽然我无法弄清楚到底是怎么做的:

<?php

$original = array (
            array ("title" => "one",
                  "color" => "blue"
                  ),
            array ("title" => "two",
                   "color" => "green"
                  )
                );


$merged = array();

$str = "000three000red0!000four000white0!000five000black0!";
$pat = "/\d+(\D+)\d+(\D+)\d!/um";

preg_match($pat, $str, $match);

foreach($match as $result) {

    $merged = array_merge($original,array("title" => $match[1], "color" => $match[2]));

    print_r($merged);

}

第一个问题是,似乎只是拿起第一场比赛,第二个是没有被添加到$ merged。我希望将其输出为:

Array
(
    [0] => Array
        (
            [title] => one
            [color] => blue
        )

    [1] => Array
        (
            [title] => two
            [color] => green
        )

    [2] => Array
        (
            [title] => three
            [color] => red
        )

    [3] => Array
        (
            [title] => four
            [color] => white
        )
    [4] => Array
        (
            [title] => five
            [color] => black
        )

)

2 个答案:

答案 0 :(得分:1)

完整,包括preg_match_all:

$original = array (
        array ("title" => "one",
              "color" => "blue"
              ),
        array ("title" => "two",
               "color" => "green"
              )
            );


$merged = array();

$str = "000three000red0!000four000white0!000five000black0!";
$pat = "/\d+(\D+)\d+(\D+)\d!/um";

preg_match_all($pat, $str, $match);

$merged = $original;
$i = 0;
foreach($match[1] as $result) {
    $merged[] = array("title" => $match[1][$i], "color" => $match[2][$i]);
    $i++;
}

print_r($merged);

结果:

    Array (
        [0] => Array
            (
                [title] => one
                [color] => blue
            )

        [1] => Array
            (
                [title] => two
                [color] => green
            )

        [2] => Array
            (
                [title] => three
                [color] => red
            )

        [3] => Array
            (
                [title] => four
                [color] => white
            )

        [4] => Array
            (
                [title] => five
                [color] => black
            )

    )

答案 1 :(得分:0)

问题是:

foreach($match as $result) {

    $merged = array_merge($original,array("title" => $match[1], "color" => $match[2]));

    print_r($merged);

}

在循环的每个步骤中,您将原始数组与新数组合并,并将输出保存到合并数组中,因此实际上您不会更改原始数组,并且每次再次设置合并值时。

将其更改为:

$merged = array(); // or $merged = $original; depending on your exact needs

foreach($match as $result) {

    $merged = array_merge($merged,array("title" => $match[1], "color" => $match[2]));

    print_r($merged);

}