使用PHP进行数组迭代和合并

时间:2011-09-21 04:49:57

标签: php arrays multidimensional-array foreach

我有一个像:

这样的数组
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [productid] => 141
                    [fieldid] => 2
                    [value] => Laptop
                )

            [1] => Array
                (
                    [productid] => 191
                    [fieldid] => 2
                    [value] => Books
                )

            [2] => Array
                (
                    [productid] => 177
                    [fieldid] => 2
                    [value] => Printer
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [productid] => 141
                    [fieldid] => 1
                    [value] => 3
                )

            [1] => Array
                (
                    [productid] => 191
                    [fieldid] => 1
                    [value] => 4
                )

            [2] => Array
                (
                    [productid] => 177
                    [fieldid] => 1
                    [value] => 2
                )

        )

)`

我希望修改此数组,如下所示:

Array
(
    [0] => Array
        (
            [productid] => 141
            [fieldid] => 2
            [value] => Laptop
        )

    [1] => Array
        (
            [productid] => 191
            [fieldid] => 2
            [value] => Books
        )

    [2] => Array
        (
            [productid] => 177
            [fieldid] => 2
            [value] => Printer
        )

    [3] => Array
        (
            [productid] => 141
            [fieldid] => 1
            [value] => 3
        )

    [4] => Array
        (
            [productid] => 191
            [fieldid] => 1
            [value] => 4
        )

    [5] => Array
        (
            [productid] => 177
            [fieldid] => 1
            [value] => 2
        )
)

只需删除外部数组并将所有数组块合并为一个。这可能在PHP中。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

一种方法可能是这样的:

让我们说$items是你原来的数组,

$new_items = array();
foreach($items as $item)
{
    $new_items = array_merge($new_items,array_values($item));
}

答案 1 :(得分:1)

是的,您可以使用以下方法来做到这一点。非常简单。

//let the older array be $array
var $newArray = array();  //new array(all itms will be taken to this array)      
foreach($array as $key->$value){
    foreach($value as $key->$innervalue){
            $newArray[] = $innervalue;
             }

    }