I am using laravel framework to develop API's , i have one scenario i need to merge arrays dynamically based on the keys for that one i am using like following,except two keys in array all remaining keys has to be merge in customizedarray for that i am using array_merge_recursive function it's merging but keys are missing
foreach($attributes as $key => $value){
if(!in_array($key,['addressinfo','customizedarray'])){
$attributes['customizedarray'] = array_merge_recursive(json_decode($attributes['customizedarray'],true),$value);
}
}
Dump before merging
array:3 [
"Additional Info 3" => array:2 [
698 => "[email protected]"
711 => "edde"
]
"addressinfo" => "{"85":"Invoice","86":"AP","87":"add1","88":52300,"89":"Add2","90":"UK","91":"Alaska","92":"COL","632":"enabled","631":33,"633":23}"
"customizedarray" => "{"75":"Mr","76":8464044255,"77":"sai","78":7901001572,"79":"tarun","81":"admin","82":"[email protected]","83":"enabled","84":1234,"583":"A","594":7878787,"628":"USD","596":"Enabled","597":"sai2@#gmail.com","593":78787878,"595":"test","588":66666666,"591":"www.google.com","592":10,"626":4,"590":"85-85-2022"}"
]
Dump After merging
for following array the keys are missing but values are merged , in my case i need to merge both keys and values into same key
array:3 [
"Additional Info 3" => array:2 [
698 => "[email protected]"
711 => "edde"
]
"addressinfo" => "{"85":"Invoice","86":"AP","87":"add1","88":52300,"89":"Add2","90":"UK","91":"Alaska","92":"COL","632":"enabled","631":33,"633":23}"
"customizedarray" => array:23 [
0 => "Mr"
1 => 8464044255
2 => "sai"
3 => 7901001572
4 => "tarun"
5 => "admin"
6 => "[email protected]"
7 => "enabled"
8 => 1234
9 => "A"
10 => 7878787
11 => "USD"
12 => "Enabled"
13 => "sai2@#gmail.com"
14 => 78787878
15 => "test"
16 => 66666666
17 => "www.google.com"
18 => 10
19 => 4
20 => "85-85-2022"
21 => "[email protected]"
22 => "edde"
]
]
CodePudding user response:
Simply add those two arrays like following
foreach($attributes as $key => $value){
if(!in_array($key,['addressinfo','customizedarray'])){
$attributes['customizedarray'] = json_decode($attributes['customizedarray'],true) $value;
}
}