简体   繁体   中英

Combine multiple array into one array using php

I'm trying to make an array with multiple arrays, the individual arrays are don't have key's the name of the array will be the key of the new array.

For example :

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

I want to display this two arrays into like below

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

);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM