note 80009 deleted from ref.array by felipe

From: Date: Sun, 30 Dec 2007 19:31:33 +0000
Subject: note 80009 deleted from ref.array by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-134538@lists.php.net to get a copy of this message
Note Submitter: php atdomain yereth incountry nl ---- I was looking for a array transpose but surprisingly it's not in PHP. Here's my humble version: <?php function array_transpose($array, $selectKey = false) { if (!is_array($array)) return false; $return = array(); foreach($array as $key => $value) { if (!is_array($value)) return $array; if ($selectKey) { if (isset($value[$selectKey])) $return[] = $value[$selectKey]; } else { foreach ($value as $key2 => $value2) { $return[$key2][$key] = $value2; } } } return $return; } ?> As you can see, it does a bit more. You can submit a Key name, which should be selected from the transposed array, if you only want that specific key. Examples: <?php $people = array( array('id' => 1, 'name' => 'john', 'occupation' => 'unemployed'), array('id' => 5, 'name' => 'pete', 'occupation' => 'dentist'), array('id' => 19, 'name' => 'hank', 'occupation' => 'software developer') ); print_r(array_transpose($people)); print_r(array_transpose($people, 'name')); ?> Will output: Array( [id] => Array( [0] => 1 [1] => 5 [2] => 19 ) [name] => Array ( [0] => john [1] => pete [2] => hank ) [occupation] => Array ( [0] => unemployed [1] => dentist [2] => software developer ) ) Array ( [0] => john [1] => pete [2] => hank ) I use it all the time, especially for structured array data such as this.

« previous php.notes (#134538) next »