使用PHP和preg_match进行字母数字排序


alphanumeric sorting with php and preg_match

我有一个名为$itemArray[]的数组,其中包含一组字符串,例如:

myItem_1,
myItem_2,
myItem_3,
myItem_4,
anotherName_1,
anotherName_2,
anotherName_3,
anotherName_4

我还有下面的代码,它遍历数组并过滤掉包含'myItem'的代码。这个循环可以工作,但是它返回的结果顺序不同。有没有一种方法来排序数组的结果呢是按字母数字排列的吗?

foreach($itemArray as $item) {
  if (preg_match('/myItem/',$item))
    echo '$item';
}

我对php没有太多的经验,我会非常感谢你的帮助!谢谢你!

PHP支持很多排序数组的方法,看看它们是如何工作的。您可以将其作为asort($itemArray)运行。

解决这个问题的正确方法是在输出之前对数组进行排序。类似以下语句:

asort($itemArray);
foreach($itemArray as $item) {
  if (preg_match('/myItem/',$item))
    array[index++] = $item;
}