note 28042 deleted from ref.array by sniper

From: Date: Sat, 18 Oct 2003 18:02:40 +0000
Subject: note 28042 deleted from ref.array by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-58833@lists.php.net to get a copy of this message
Note Submitter: jon@pixelmajik.com ---- A little function which rotates a 2d array (or, basically, swaps the first two keys of a multidimensional array). Oh, and it's hash-friendly (hence my use of foreach instead of for). Example 1: $a['alice']['gender'] = 'f'; $a['alice']['status'] = 'single'; $a['bob']['gender'] = 'm'; $a['bob']['status'] = 'married'; $a['charles']['gender'] = 'm'; $a['charles']['status']='divorced'; $b = array_rotate_2d($a); print_r($b) results in: Array ( [gender] => Array ( [alice] => f [bob] => m [charles] => m ) [status] => Array ( [alice] => single [bob] => married [charles] => divorced ) ) As you may see, it's useful for displaying rows as columns (example 2, below) or reorganizing data (example 1, above). Example 2: $qid = mysql_query("SELECT ... FROM table"); while($row = mysql_fetch_array($qid, MYSQL_ASSOC)) $table[] = $row; $rotated_table = array_rotate_2d($table); foreach($table AS $row) { echo join("\t", $row)."\n"; } Code: function array_rotate_2d($old) { // rotates a 2d array such that $array[$i][$j] becomes $array[$j][$i]. (useful for displaying rows as columns, for example) foreach($old AS $k1=>$v1) foreach($v1 AS $k2=>$v2) $new[$k2][$k1] = $v2; return $new; }

« previous php.notes (#58833) next »