1630082
1630082

Reputation: 49

Merge and transpose data from two flat associative arrays to form a new 2d array

I'm trying to make an array by merging multiple arrays by column.

The individual arrays don't have keys, the arrays' variable name will determine the associative keys in the rows of the new array.

For example:

$product_name = ['0' => 'product1', '2' => 'product2'];
$product_id = ['0' => '1', '2' => '2'];

I want to display this two arrays into like below

$newarray = [
    ['product_id' => 1, 'product_name' => 'product1'],
    ['product_id' => 2, 'product_name' => 'product2'],
];

Upvotes: 0

Views: 53

Answers (1)

jonnu
jonnu

Reputation: 728

Code:

$product_name = array('0'=>'product1','2'=>'product2');
$product_id   = array('0'=>'1','2'=>'2');

$new_array = array();
foreach (array_keys($product_id) as $key) {
    $new_array[] = array(
        'product_id'   => $product_id[$key],
        'product_name' => $product_name[$key]
    );
}

print_r($new_array);

Result:

Array
(
    [0] => Array
        (
            [product_id] => 1
            [product_name] => product1
        )

    [1] => Array
        (
            [product_id] => 2
            [product_name] => product2
        )
)

Upvotes: 1

Related Questions