Home > Enterprise >  Associative Array merge in php
Associative Array merge in php

Time:10-09

I want to merge array in php. Here I pushed array value to a master array. Here my master array is

$master_array = [
  56 => [
    'item_name'=> 'xyz',
    'item_code'=> 56,
  ]
];

sub array which I want to push

$sub_array = [
  60 => [
    'item_name'=> 'xy',
    'item_code'=> 60,
  ]
];

And finally array should be

$array = [
  56 => [
    'item_name'=> 'xyz',
    'item_code'=> 56,
  ],
  60 => [
    'item_name'=> 'xy',
    'item_code'=> 60,
  ]
];

I tried with

array_push( $master_array , $sub_array );

But it's always replacing

CodePudding user response:

You can use operator: $array = $master_array $sub_array;

$master_array = [
  56 => [
    'item_name'=> 'xyz',
    'item_code'=> 56,
  ]
];

$sub_array = [
  60 => [
    'item_name'=> 'xy',
    'item_code'=> 60,
  ]
];

$array = $master_array   $sub_array;

print_r($array);

The result will be:

Result

CodePudding user response:

Use php function array_merge()

$master_array = [
  56 => [
    'item_name'=> 'xyz',
    'item_code'=> 56,
  ]
];

$sub_array = [
  60 => [
    'item_name'=> 'xy',
    'item_code'=> 60,
  ]
];

$array = array_merge($master_array , $sub_array);

  •  Tags:  
  • php
  • Related