note 28042 added to ref.array
| From: | jon at pixelmajik dot com | Date: | Mon, 30 Dec 2002 19:10:20 +0000 |
| Subject: | note 28042 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-41489@lists.php.net to get a copy of this message | ||
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;
}
--
http://www.php.net/manual/en/ref.array.php
http://master.php.net/manage/user-notes.php?action=edit+28042
http://master.php.net/manage/user-notes.php?action=delete+28042
http://master.php.net/manage/user-notes.php?action=reject+28042