note 107097 modified in function.array-flip by danbrown

From: Date: Fri, 06 Jan 2012 19:05:18 +0000
Subject: note 107097 modified in function.array-flip by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-185393@lists.php.net to get a copy of this message
I needed a way to flip a multidimensional array and came up with this function to accomplish the task. I hope it helps someone else. <?php function multi_array_flip($arrayIn, $DesiredKey, $DesiredKey2=false, $OrigKeyName=false) { $ArrayOut=array(); foreach ($arrayIn as $Key=>$Value) { // If there is an original key that need to be preserved as data in the new array then do that if requested ($OrigKeyName=true) if ($OrigKeyName) $Value[$OrigKeyName]=$Key; // Require a string value in the data part of the array that is keyed to $DesiredKey if (!is_string($Value[$DesiredKey])) return false; // If $DesiredKey2 was specified then assume a multidimensional array is desired and build it if (is_string($DesiredKey2)) { // Require a string value in the data part of the array that is keyed to $DesiredKey2 if (!is_string($Value[$DesiredKey2])) return false; // Build NEW multidimensional array $ArrayOut[$Value[$DesiredKey]][$Value[$DesiredKey2]]=$Value; } // Build NEW single dimention array else $ArrayOut[$Value[$DesiredKey]][]=$Value; } return $ArrayOut; }//end multi_array_flip ?> --was-- I needed a way to flip a multidimensional array and came up with this function to accomplish the task. I hope it helps someone else. function multi_array_flip($arrayIn, $DesiredKey, $DesiredKey2=false, $OrigKeyName=false) { $ArrayOut=array(); foreach ($arrayIn as $Key=>$Value) { // If there is an original key that need to be preserved as data in the new array then do that if requested ($OrigKeyName=true) if ($OrigKeyName) $Value[$OrigKeyName]=$Key; // Require a string value in the data part of the array that is keyed to $DesiredKey if (!is_string($Value[$DesiredKey])) return false; // If $DesiredKey2 was specified then assume a multidimensional array is desired and build it if (is_string($DesiredKey2)) { // Require a string value in the data part of the array that is keyed to $DesiredKey2 if (!is_string($Value[$DesiredKey2])) return false; // Build NEW multidimensional array $ArrayOut[$Value[$DesiredKey]][$Value[$DesiredKey2]]=$Value; } // Build NEW single dimention array else $ArrayOut[$Value[$DesiredKey]][]=$Value; } return $ArrayOut; }//end multi_array_flip http://php.net/manual/en/function.array-flip.php

« previous php.notes (#185393) next »