note 108544 added to function.array-multisort
| From: | info at marcopanichi dot com | Date: | Sat, 05 May 2012 10:41:26 +0000 |
| Subject: | note 108544 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-187482@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 93.65.143.176
----
Manual Page -- http://www.php.net/manual/en/function.array-multisort.php
Edit -- https://master.php.net/note/edit/108544
Del: integrated -- https://master.php.net/note/delete/108544/integrated
Del: useless -- https://master.php.net/note/delete/108544/useless
Del: bad code -- https://master.php.net/note/delete/108544/bad+code
Del: spam -- https://master.php.net/note/delete/108544/spam
Del: non-english -- https://master.php.net/note/delete/108544/non-english
Del: in docs -- https://master.php.net/note/delete/108544/in+docs
Del: other reasons-- https://master.php.net/note/delete/108544
Reject -- https://master.php.net/note/reject/108544
Search -- https://master.php.net/manage/user-notes.php