How to make value as a key in multi dimensional array in php

For change key of multi dimensional array according to value of inner array just put below function into your script and use it..

if(!function_exists('array_keyBy'))
{
function array_keyBy($array , $keyBy)
{
if(!empty($array) && count($array) >0 )
{
$tempArray = [];
foreach($array as $key => $value)
{
if(!is_array($value))
{
$value = (array) $value;
}
if(isset($value[$keyBy]) && $value[$keyBy]!='' && !is_array($value[$keyBy]))
{
$tempArray[$value[$keyBy]] = $value;
}
}
$array = $tempArray;
}
return $array;
}
}


For example: - I have an array as like below and i want to change key of multi dimensional array by value of name key.

$person = array
  (
  array(
'name' => 'Romal',
'Age' => '34'
),
  array(
'name' => 'Anil',
'Age' => '24'
),
  );


Now i call above function like below:- 

 $newpersons = array_keyBy($person,'name'); 

Now output of $newpersons is like below..

Array
(
    [Romal] => Array
        (
            [name] => Romal
            [Age] => 34
        )

    [Anil] => Array
        (
            [name] => Anil
            [Age] => 24
        )

)

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