samir chauhan
samir chauhan

Reputation: 1543

Array iteration and merging using PHP

I have an array like : `

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
                )

        )

)`

I want this array to be modified and looks like the following :

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
        )
)

Just remove the outer array and combine all chunks of array into one. Is this possible in php. Thanks in advance.

Upvotes: 0

Views: 85

Answers (2)

Radheshyam Nayak
Radheshyam Nayak

Reputation: 1068

Yes you can use the following method to do that.Quite simple.

//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;
             }

    }

Upvotes: 1

Vikk
Vikk

Reputation: 3363

One approach could be this:

Lets say $items is your original array,

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

Upvotes: 1

Related Questions