How To Convert Multi Dimensional Key Value Array To Key Value Pair Array In Php

Here we learn about how to convert multidimensional key-value array to key-value pair array in PHP.

Here is an example of a multi-dimensional array.

<?php
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] => test1@gmail.com,test2@gmail.com
  )
  [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] => 10:10:46
  )
)
?>

Now you create one function for convert array to key-value pair array.

<?php
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 you can pass your multidimensional array as $mainArray, $keyLabel as key for new array and $valueLabel as value for the new array.

For example: $keyLabel = ‘custom_key’; and $valueLabel = ‘custom_value’;

<?php $storeMeta = arrangeArrayPair( $storeMeta, 'custom_key', 'custom_value' ); ?>

Below final output:

<?php
Array(
  [tax] => 13
  [currency] => CAD
  [order_email] => test1@gmail.com,test2@gmail.com
  [timezone] => America/New_York
  [is_ordering_available] => 1
  [store_number] => 760
  [is_storeinfo_editable] => 0
  [breakfast_end_time] => 10:10:46
)
?>

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories