I have two arrays like the following.
$alerts_array=array(1) {
[0]=> array(11) {
["CustomAlertsID"]=> int(3)
["CustomAlerts_Name"]=> string(10) "title demo"
["CustomAlerts_PublishDate"]=> string(10) "2016-07-03"
["CustomAlerts_ExpiryDate"]=> string(10) "2016-07-21"
}
}
$singlebtn_array =array(3) {
["button_text0"]=> string(16) "Button Name1only"
["button_text1"]=> string(12) "button name2"
["button_text2"]=> string(16) "button name3_new"
}
I have merged the two arrays into a single multidimensional array which looks like following
$alerts_array = array_merge($alerts_array,$singlebtn_array);
array(4) { [0]=> array(11)
{ ["CustomAlertsID"]=> int(3)
["CustomAlerts_Name"]=> string(10) "title demo"
["CustomAlerts_PublishDate"]=> string(10) "2016-07-03"
["CustomAlerts_ExpiryDate"]=> string(10) "2016-07-21"
}
[1]=> array(1)
{ ["button_text0"]=> string(16) "Button Name1only" }
[2]=> array(1)
{ ["button_text1"]=> string(12) "button name2" }
[3]=> array(1) { ["button_text2"]=> string(16) "button name3_new" } }
I need both keys and values in the new flattened array
I need it like this:
array(4) { [0]=> array(11)
{ ["CustomAlertsID"]=> int(3)
["CustomAlerts_Name"]=> string(10) "title demo"
["CustomAlerts_PublishDate"]=> string(10) "2016-07-03"
["CustomAlerts_ExpiryDate"]=> string(10) "2016-07-21"
["button_text0"]=> string(16) "Button Name1only"
["button_text1"]=> string(12) "button name2"
["button_text2"]=> string(16) "button name3_new" }}
I have usedthe following code for combining.
$newArr = array();
foreach ($alerts_array as $key=>$tmp) {
$newArr = array_merge($newArr, array_values($tmp));
}
The $newArr
is giving me the result ,but keys are lost
Simply merge the first key [0]
of your $alerts_array
, like this:
$alerts_array = array_merge($alerts_array[0], $singlebtn_array);
That will output:
array(7) {
["CustomAlertsID"]=>
int(3)
["CustomAlerts_Name"]=>
string(10) "title demo"
["CustomAlerts_PublishDate"]=>
string(10) "2016-07-03"
["CustomAlerts_ExpiryDate"]=>
string(10) "2016-07-21"
["button_text0"]=>
string(16) "Button Name1only"
["button_text1"]=>
string(12) "button name2"
["button_text2"]=>
string(16) "button name3_new"
}
Also see the working demo here.
To get what you want because alerts is an array of arrays:
$alerts_array = array_merge($alerts_array[0],$singlebtn_array);
But with an array of arrays you will probably want a loop. Not sure if each one would be the same thing or if you will have multiples but this will help you.
$alerts_array; //Your array for arrays
singlebtn_array; //Whatever this is
$flattened_alerts_singlebtn = array();
foreach($alerts_array as $alert_array){
//This will be every array in the alerts as your flattened
//array with the singlebtn
$flattened_alerts_singlebt[] = array_merge($alert_array,$singlebtn_array);
}
You can then loop $flattened_alerts_singlebtn
to get each falttened array that could exist.