phparraysmultidimensional-arraydata-structures

Convert a flat associative array into a two-column 2d array with predefined column names


I would like to know how to combine and overwrite the already existed array value in php.

My current array look like:

Array
(
    [1149] => 3
    [4108] => 5
)

As shown above values, I need the expected result in php as below:

Array
(
    [0] => Array
        (
            [offer_id] => 1149
            [quantity] => 3
        )

    [1] => Array
        (
            [offer_id] => 4108
            [quantity] => 5
        )
)

Solution

  • How about:

    $result = [];
    foreach (
        [
            1149 => 3,
            4108 => 3,
        ] as $key => $value
    ) {
        $result[] = [
            'offer_id' => $key,
            'quantity' => $value,
        ];
    }
    
    print_r($result);