note 108544 deleted from function.array-multisort by danbrown

From: Date: Thu, 10 May 2012 16:48:20 +0000
Subject: note 108544 deleted from function.array-multisort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-187592@lists.php.net to get a copy of this message
Note Submitter: info at marcopanichi dot com ---- Using jimpoz at jimpoz dot com note, I developed a function to order a tree. My function accept three arguments: > $a = array > $orderby = an order string written in sql language > $children_key = name of the eventual column where eventual children node are saved And could be used so: <?php $array = array_multiorderby( $array, "weight_node ASC", 'children_nodes' ): ?> Here the function: <?php function array_multiorderby( $data, $orderby, $children_key=false ) { // parsing orderby $args = array(); $x = explode( ' ', str_replace( ',', ' ', $orderby ) ); foreach( $x as $item ) { $item = trim( $item ); if( $item=='' ) continue; if( strtolower($item)=='asc' ) $item = SORT_ASC; else if( strtolower($item)=='desc' ) $item = SORT_DESC; $args[] = $item; } // order foreach ($args as $n => $field) { if (is_string($field)) { $tmp = array(); foreach ($data as $key => $row) $tmp[$key] = $row[$field]; $args[$n] = $tmp; } } $args[] = &$data; call_user_func_array('array_multisort', $args); $data = array_pop($args); // order children if( $children_key ) { foreach( $data as $k=>$v ) if( is_array($v[$children_key]) ) $data[$k][$children_key] = array_multiorderby( $v[$children_key], $children_key, $orderby ); } // return return $data; } ?>

« previous php.notes (#187592) next »