Claus Nielsen Claus Nielsen - 13 days ago 8
PHP Question

Sort PHP Array based on another Array (using substr("String",-3,1) function)

I have an array like

$unsorted = Array(
"0" =>"3470U11",
"1" =>"3470E11",
"2" =>"3470S13",
"3" =>"3470G11",
"4" =>"3470S12",
"5" =>"3470S11",
"6" =>"3470E12",
"7" =>"3470U12",
"8" =>"3470G13",
"9" =>"3470G12",
"10" =>"3470E13",
"11" =>"3470U13"
);

$sortBy = array('G','D','S','U','E','T','A','L');


I need to sort the array by the substr($value,-3,1) in the order listed in $sortBy so the result becomes like

$sorted = Array(
"0" => "3470G11",
"1" => "3470G12",
"2" => "3470G13",
"3" => "3470S11",
"4" => "3470S12",
"5" => "3470S13",
"6" => "3470U11",
"7" => "3470U12",
"8" => "3470U13",
"9" => "3470E11",
"10" =>"3470E12",
"11" =>"3470E13"
);

Answer

usort

(PHP 4, PHP 5, PHP 7) usort — Sort an array by values using a user-defined comparison function

<?php
$unsorted = Array(
"0" =>"3470U11",
"1" =>"3470E11",
"2" =>"3470S13",
"3" =>"3470G11",
"4" =>"3470S12",
"5" =>"3470S11",
"6" =>"3470E12",
"7" =>"3470U12",
"8" =>"3470G13",
"9" =>"3470G12",
"10" => "s3470E13",
"11" => "s3470U13"
);

//$a and $b -> two elts of the array
function cmp ($a,$b){

	$substring_a = substr($a, -3,1);
	$substring_b = substr($b, -3,1);
	
	$sortArr = array('G','D','S','U','E','T','A','L');
	
	$key_a = array_search($substring_a, $sortArr);
	$key_b = array_search($substring_b, $sortArr);
	
	if($key_a == $key_b){
		return strcmp(substr($a, -2),substr($b, -2));
		
	}	
	return $key_a > $key_b;

}

usort($unsorted, "cmp");
print_r($unsorted);