如何按字母顺序对数组内的每个元素进行排序[复制]

时间:2021-11-03 16:00:53

This question already has an answer here:

这个问题在这里已有答案:

For example we have the following words: hey, hello, wrong

例如,我们有以下几个字:嘿,你好,错了

$unsorted = array("eyh", "lhleo", "nrwgo");

I know that I could use asort to sort the array alphabetically, but I don't want that. I wish to take the elements of the array and sort those, so that it would become something like this:

我知道我可以使用asort按字母顺序对数组进行排序,但我不希望这样。我希望获取数组的元素并对它们进行排序,以便它会变成这样:

$sorted = array("ehy", "ehllo", "gnorw"); // each word in the array sorted

hey sorted = ehy

嘿排序= ehy

hello sorted = ehllo

你好排序= ehllo

wrong sorted = gnorw

错误排序= gnorw

As far as I know, the function sort will only work for arrays, so if you attempt to sort a word using sort, it will produce an error. If I had to assume, I will probably need to use a foreach along with strlen and a for statement or something similar, but I am not sure.

据我所知,函数sort只适用于数组,因此如果你尝试使用sort对单词进行排序,则会产生错误。如果我不得不假设,我可能需要使用foreach以及strlen和for statement或类似的东西,但我不确定。

Thanks in advance!

提前致谢!

3 个解决方案

#1


1  

function sort_each($arr) {
    foreach ($arr as &$string) {
        $stringParts = str_split($string);
        sort($stringParts);
        $string = implode('', $stringParts);
    }
    return $arr;
}

$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = sort_each($unsorted);
print_r($sorted); // returns Array ( [0] => ehy [1] => ehllo [2] => gnorw )

#2


1  

$myArray = array("eyh", "lhleo", "nrwgo");
array_walk(
     $myArray,
     function (&$value) {
         $value = str_split($value);
         sort($value);
         $value = implode($value);
     }
);
print_r($myArray);

#3


0  

Try this

$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = array();
foreach ($unsorted as $value) {
$stringParts = str_split($value);
sort($stringParts);
$sortedString =  implode('', $stringParts);
array_push($sorted, $sortedString);
}
print_r($sorted);

#1


1  

function sort_each($arr) {
    foreach ($arr as &$string) {
        $stringParts = str_split($string);
        sort($stringParts);
        $string = implode('', $stringParts);
    }
    return $arr;
}

$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = sort_each($unsorted);
print_r($sorted); // returns Array ( [0] => ehy [1] => ehllo [2] => gnorw )

#2


1  

$myArray = array("eyh", "lhleo", "nrwgo");
array_walk(
     $myArray,
     function (&$value) {
         $value = str_split($value);
         sort($value);
         $value = implode($value);
     }
);
print_r($myArray);

#3


0  

Try this

$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = array();
foreach ($unsorted as $value) {
$stringParts = str_split($value);
sort($stringParts);
$sortedString =  implode('', $stringParts);
array_push($sorted, $sortedString);
}
print_r($sorted);