I think this function can help you. Here all the elements of the array are sorted, starting with the last letter in parameter. Then the other elements would follow in alphabetical order.
The possibility of uppercase letters is also contemplated, both in the values of the array, and in the written letter that would be used as a search criterion.
In theory, the function does the following:
Sort the original array alphabetically with natcasesort
Convert the last letter to lowercase using strtolower
, that way it will not fail if you pass uppercase letters to it.
Do the same procedure with each value.
Use strpos
to verify if the value starts with the letter passed in parameter. If so, enter the current element in a new array $arrInicial
and remove it from the original array with unset
.
At the end, create a new $arrFinal
, composed of $arrInicial
(where the found values will be) and $arrOrigen
(where the values that were not found will be).
I hope it serves you.
Function code
VIEW DEMO IN REXTESTER
/*Función*/
function orderArrayByChar($arrOrigen, $letra)
{
natcasesort($arrOrigen);
$arrInicial=array();
$letra=strtolower($letra);
if (count($arrOrigen) > 0) {
foreach ($arrOrigen as $k => $v) {
$elValor=strtolower($v);
$siLetra = strpos($elValor, $letra) === 0;
if ($siLetra){
$arrInicial[$k]=$v;
unset($arrOrigen[$k]);
}
}
$arrFinal = $arrInicial+ $arrOrigen;
}
return $arrFinal;
}
Test code
/*Pruebas*/
echo "Array original:".PHP_EOL.PHP_EOL;
$arrDatos = array("1"=>"javax","2"=>"android","3"=>"ajax","4"=>"asp.net","5"=>"javascript","6"=>"phyton","7"=>"PHP");
print_r($arrDatos);
echo PHP_EOL.PHP_EOL."Prueba con j".PHP_EOL.PHP_EOL;
$q = 'j';//$_REQUEST["q"];
natcasesort($arrDatos);
$arrOrdenado=orderArrayByChar($arrDatos, $q);
print_r($arrOrdenado);
/*Importante usar natcasesort, si no dará problemas con las mayúsculas*/
echo PHP_EOL.PHP_EOL."Prueba con p".PHP_EOL.PHP_EOL;
$q = 'P';//$_REQUEST["q"];
$arrDatos = array("1"=>"javax","2"=>"android","3"=>"ajax","4"=>"asp.net","5"=>"javascript","6"=>"phyton","7"=>"PHP");
natcasesort($arrDatos);
$arrOrdenado=orderArrayByChar($arrDatos, $q);
print_r($arrOrdenado);
Result:
Array original:
Array
(
[1] => javax
[2] => android
[3] => ajax
[4] => asp.net
[5] => javascript
[6] => phyton
[7] => PHP
)
Prueba con j
Array
(
[5] => javascript
[1] => javax
[3] => ajax
[2] => android
[4] => asp.net
[7] => PHP
[6] => phyton
)
Prueba con p
Array
(
[7] => PHP
[6] => phyton
[3] => ajax
[2] => android
[4] => asp.net
[5] => javascript
[1] => javax
)