如何在php中对合并后的数组进行排序


How to sort the merged arrays in php?

我有两个数组

使用arraymerge函数,合并了两个数组。然后我需要对合并后的数组进行排序。

这是我的php代码

<?php
$file=file("master.bib");
$c=count($file);

//count of article
$key = '@article';
foreach ($file as $l => $line) {
    if (strpos($line,$key) !== false) {
       $l++;
       $typeart[]= $l;
          }
}//end-count of article
$key = '}';
foreach ($file as $l => $line) {
    if (strpos($line,$key) === 0) {
       $l++;
       $typeclose[]= $l;
          }
}

$p=array_merge($typeart,$typeclose);
echo sort($p);
?>

但是我得到了输出1。我不知道这里出了什么问题。

sort()文档中可以看到,您的数组是引用

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
//                ^ & means reference

这意味着当方法运行时,原始数组将发生更改。您也可以从文档中看到,它返回以下内容:

成功时返回TRUE,失败时返回FALSE

因此,本质上(就像文档中的示例一样)正确的用法是:

sort($p); // $p will now be sorted

或者更详细的

if (sort($p)) {
    // $p is now sorted
} else {
    // $p could not be sorted for whatever reason
}

sort直接更改您的数组,因此您应该使用print_r($p)来检查数组,如下所示:

sort($p); //Array Sorted and contents changed directly no return :)
print_r($p);