How Convert multi dimensional key value array to key value pair array in php

Today here i am sharing with you how to convert multi dimensional key value array to key value pair array. Below is example of multi dimensional array.

Array ( [0] => Array ( [custom_key] => tax [custom_value] => 13 ) [1] => Array ( [custom_key] => currency [custom_value] => CAD ) [2] => Array ( [custom_key] => order_email [custom_value] => gobietesting@gmail.com,hiren@unoindia.co ) [3] => Array ( [custom_key] => timezone [custom_value] => America/New_York ) [4] => Array ( [custom_key] => is_ordering_available [custom_value] => 1 ) [5] => Array ( [custom_key] => store_number [custom_value] => 760 ) [6] => Array ( [custom_key] => is_storeinfo_editable [custom_value] => 0 ) [7] => Array ( [custom_key] => breakfast_end_time [custom_value] => 05:30:00 ) )


Now you need to put one function for convert array to key value pair array.
if(!function_exists('arrangeArrayPair')) {
function arrangeArrayPair($mainArray,$keyLabel,$valueLabel) {
$newArray = array_combine(
array_map( function($value) use($keyLabel){
return $value[$keyLabel];
}, $mainArray )
, array_map( function($value) use($valueLabel){
return $value[$valueLabel];
}, $mainArray ) );
return $newArray;
}
}

Now for call this function you need to pass your multidimensional array as $mainArray
$keyLabel as key for new array and $valueLabel as value for new array.
For example to convert above array using this function i used $keyLabel = 'custom_key';
and $valueLabel = 'custom_value';

$storeMeta = arrangeArrayPair($storeMeta,'custom_key','custom_value');

And final output is as per below
Array
(
    [tax] => 13
    [currency] => CAD
    [order_email] => gobietesting@gmail.com,hiren@unoindia.co
    [timezone] => America/New_York
    [is_ordering_available] => 1
    [store_number] => 760
    [is_storeinfo_editable] => 0
    [breakfast_end_time] => 05:30:00
)



Comments

Popular posts from this blog

How to add image option in nav menu in wordpress

How to add a custom email functionality in woocommerce,wordpress for example new email template for shipping order

How to change user id on checkout page for assign order to different user in woocommerce wordpress