note 98742 added to function.shuffle

From: Date: Sun, 04 Jul 2010 17:39:37 +0000
Subject: note 98742 added to function.shuffle
Groups: php.notes 
Request: Send a blank email to php-notes+get-170694@lists.php.net to get a copy of this message
This function shuffles an associative array recursive. <?php /** * Shuffles an associative array recursive * @author Mogria <m0gr14@gmail.com> * @param array $array * @return array * */ function rec_assoc_shuffle($array) { $ary_keys = array_keys($array); $ary_values = array_values($array); shuffle($ary_values); foreach($ary_keys as $key => $value) { if (is_array($ary_values[$key]) AND $ary_values[$key] != NULL) { $ary_values[$key] = rec_assoc_shuffle($ary_values[$key]); } $new[$value] = $ary_values[$key]; } return $new; } ?> Example of use: <?php $array = Array( 1, Array( 1, 2, 3, 4, Array( 1, 2, 3, 4, 5 ) ), 2, 3, Array( 0, 1, Array( 1, 2, 3, 4, Array( 1, 6, 5, 2, 1, 3 ) ) ), 4, 5, 6, 7 ); $array = rec_assoc_shuffle($array); echo '<pre>'; print_r($array); echo '</pre>'; /* Returns: Array ( [0] => 6 [1] => 5 [2] => Array ( [0] => 1 [1] => 3 [2] => Array ( [0] => 3 [1] => 1 [2] => 2 [3] => 4 [4] => 5 ) [3] => 2 [4] => 4 ) [3] => 3 [4] => Array ( [0] => Array ( [0] => 3 [1] => 1 [2] => 4 [3] => Array ( [0] => 5 [1] => 1 [2] => 3 [3] => 6 [4] => 1 [5] => 2 ) [4] => 2 ) [1] => 1 [2] => 0 ) [5] => 2 [6] => 1 [7] => 4 [8] => 7 ) */ ?> ---- Server IP: 62.2.182.223 Probable Submitter: 62.203.132.178 ---- Manual Page -- http://www.php.net/manual/en/function.shuffle.php Edit -- https://master.php.net/note/edit/98742 Del: integrated -- https://master.php.net/note/delete/98742/integrated Del: useless -- https://master.php.net/note/delete/98742/useless Del: bad code -- https://master.php.net/note/delete/98742/bad+code Del: spam -- https://master.php.net/note/delete/98742/spam Del: non-english -- https://master.php.net/note/delete/98742/non-english Del: in docs -- https://master.php.net/note/delete/98742/in+docs Del: other reasons-- https://master.php.net/note/delete/98742 Reject -- https://master.php.net/note/reject/98742 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#170694) next »