Two Dimensional Array Key Swap in PHP

Example: array[key1][key2] → array[key2][key1]

This function takes a two dimensional array[x][y], swaps the first key with the second key so the values can be referenced using array[y][x]. It was also added as a user contributed note to the PHP: Array Manual on php.net’s website on October 10, 2009.

#

function array_two_key_swap( $two_dimensional_array ) {

	/*
		Writen by: Leonardo Martinez
		Contact: http://www.leonardomartinez.com/contact/

		Created: 10-10-2009
		Modified: 10-15-2009

		This function takes a two dimensional array[x][y], swaps the first
		key with the second key so the values can be referenced using array[y][x].

		Example:
					samplearray['directiory'][0] = "myicons";
					samplearray['directiory'][1] = "myicons";
					samplearray['directiory'][2] = "myiconsold";
					samplearray['directiory'][3] = "myiconsold";

					samplearray['filename'][0] = "hat.png";
					samplearray['filename'][1] = "dog.png";
					samplearray['filename'][2] = "mice.png";
					samplearray['filename'][3] = "rat.png";

		The above array converts to:

					newarray[0]['filename'] 	= "hat.png";
					newarray[0]['directiory'] 	= "myicons";
					newarray[1]['filename'] 	= "dog.png";
					newarray[1]['directiory'] 	= "myicons";
					newarray[2]['filename'] 	= "mice.png";
					newarray[2]['directiory'] 	= "myiconsold";
					newarray[3]['filename'] 	= "rat.png";
					newarray[3]['directiory'] 	= "myiconsold";

	*/

	$keys = array_keys( $two_dimensional_array );

	$array_swaped = array();

	foreach( $two_dimensional_array[$keys[0]] as $key_counter => $value1 ) {

		$temp_array = array();

		foreach( $keys as $key) {
			$temp_array[$key] = $two_dimensional_array[$key][$key_counter];
		}

		$array_swaped[] = $temp_array;
	}

	return $array_swaped;
}

Comments are closed.