Asked 7 years ago
18 Dec 2016
Views 4264
noob

noob posted

how to use array_flip function with multidimensional array in php

trying to flip the multidimensional array in php

$a=array("a",array("b","c","d"),"e","f");
array_flip($a);


and i got warning that can only flip string and integer

Warning: array_flip() [function.array-flip]: Can only flip STRING and INTEGER values! 


so basically array_flip cant work with multidimensional array .

so is there any other function will can work with flipping multidimensional array in php or any custom code which can help .


Nilesh

Nilesh
answered Nov 30 '-1 00:00

i used this function many time for flipping multidimensional array.


function multidimensional_array_flip($array, $KeyToFlip, $KeyToFlip2=false, $Keep_Original_Key=false) {
$flipped_array=array();
foreach ($array as $Key=>$Value)
    { 
        if ($Keep_Original_Key) $Value[$Keep_Original_Key]=$Key;
         if (!is_string($Value[$KeyToFlip])) return false;

          if (is_string($KeyToFlip2))
        {
              if (!is_string($Value[$KeyToFlip2])) return false;

              $flipped_array[$Value[$KeyToFlip]][$Value[$KeyToFlip2]]=$Value;
        }

		
          else $flipped_array[$Value[$KeyToFlip]][]=$Value;
    }
return $flipped_array;
} 


how to use multidimensional_array_flip . see below


	$d=multidimensional_array_flip($array_pages,1);

if multidimensional array it will flip with second index in key in array.
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

for two dimensional array , made function multiflip which work like charm.
its good alternative of array_flip

$a=array("A"=>"a",array("B"=>"b","C"=>"c","D"=>"d"),"E"=>"e","F"=>"f");
$extraArray=array();
function multiflip($a){
 	if(is_array($a)){
		foreach($a as $key=>$value){
			if(is_array($value)){
				$uniquekey="Array".rand(1,100);
				$extraArray[$uniquekey]=array_flip($value);	
				$a[$key]=$uniquekey;
			}
		}
		array_flip($a);
 

		foreach($a as $key=>$value){
			if(isset($extraArray[$value])){
				$a[$key]=$extraArray[$uniquekey];
			}
		}
	}

 
	return $a;
}
$a=multiflip($a);
Post Answer