note 112141 rejected from array.sorting by googleguy
| From: | googleguy@php.net | Date: | Thu, 09 May 2013 15:58:30 +0000 |
| Subject: | note 112141 rejected from array.sorting by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-194750@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
Hi all...
So many of us have the problem of wanting to sort multi dimensional arrays by one common key...
For example:
<?php
$array1 = array( 'foo' => 1, 'bar' => 2, 'php' =>
'code' );
$array2 = array( 'foo' => 2, 'bar' => 6, 'php' =>
'coding' );
$array3 = array( 'foo' => 3, 'bar' => 9, 'php' =>
'coded' );
?>
Just imagine that these 3 arrays are in fact 3 requests to DB...
For example:
<?php
#code ignite example *coff*coff* could be worse *coff*coff*
$array1 = $this->db->query( "SELECT * FROM table1" );
$array2 = $this->db->query( "SELECT * FROM table2" );
$array3 = $this->db->query( "SELECT * FROM table3" );
#Note that all of these tables have one field name in common... could be a timestamp or something,
#and we want to use that to sort the array by timestamp ASC...
#All we have to do is merge all these into ONE array:
foreach( $array1->result_array() as $key => $val ):
$data[] = $val;
endforeach;
foreach( $array2->result_array() as $key => $val ):
$data[] = $val;
endforeach;
foreach( $array3->result_array() as $key => $val ):
$data[] = $val;
endforeach;
#And now, we call the function to sort that out.....
orderArray( $data, 'foo', 0 ); //0 is reversive ordering and 1 is normal
/**
* @desc Orders a multi dimensional array by given key name asc or desc
* @params $input <array()> multidimensional
* @params $by <string> name of the key to orderby
* @params $sortOrder <1 : 0> 1 to aSORT() and 0 to aRSORT()
* @date 2013-05-09
* @author Ricardo Goulart <goulart.g@gmail.com>
*/
function orderArray( $input = array(), $by = null, $sortOrder = 1 )
{
//Orders a multidimensional array by a common value.
if( is_array( $input ) && !empty( $by ) ):
$siblingsContainer = array();
$returnContainer = array();
foreach( $input as $key => $val ):
if( is_array( $val ) ):
$siblingsContainer[ $key.'_' ] = $val[ $by ];
endif;
endforeach;
$sortOrder == 1 ? asort( $siblingsContainer ) : arsort( $siblingsContainer );
foreach( $siblingsContainer as $key => $val ):
$returnContainer[] = $input[str_replace( "_","", $key )];
endforeach;
return $returnContainer;
else:
return false;
endif;
}
?>