How To: Sort The Keys Of An Array By The User Given Key In PHP?

Advertisement

A simple snippet to order array with a user given a key or multiple keys.

Nothing fancy on the code, first it gets the array of the key to order by and combined it later with the original array.


function rs_theme_order_array_by_key( $array, $orderby, $order = 'asc' ) {
	
	// Check if Key exist in a given Array
	if( array_key_exists( $orderby, $array ) ) {
		// copy the node before unsetting
		$newarray = array( $orderby => $array[$orderby] );

		// remove the node
		unset( $array[$orderby] );

		// combine copy with filtered array
		if( 'asc' == $order )
			$array = $newarray + array_filter( $array );
		else
			$array = array_filter( $array ) + $newarray;
	}

	// Return new ordered Array
	return $array;
}

Sort with multiple parameters


function rs_theme_order_array_by_key( $array, $orderby, $order = 'asc' ) {
	if( $orderby ) {
		$keynames = explode( '||', $orderby );
		
		// So making sure we're reading the first line first
		if( $keynames )
			$keynames = array_reverse($keynames);

		foreach( $keynames as $n ){
			if(array_key_exists($n, $lever_array)) {
				// copy the node before unsetting
				$newarray = array( $n => $lever_array[$n] );

				//remove the node
				unset( $lever_array[$n] );

				// combine copy with filtered array
				if( 'asc' == $order )
					$array = $newarray + array_filter( $array );
				else
					$array = array_filter( $array ) + $newarray;
				}
		}
	}

	// Return new ordered Array
	return $array;
}

That’s it, happy coding ^_^

Advertisement