按相同的字符串名称和索引位置排序

时间:2018-07-15 16:49:24

标签: php arrays sorting

我正在尝试对一个数组进行排序,在该数组中,我有一列包含相等的字符串,而前一列包含应根据发生情况打印的信息。我只想打印第9列的字母顺序,而不考虑第8列的字母顺序。

例如:

column 9=[rank 1, rank1, rank 2, rank2, rank 3, rank3, ...]

column 8=[CO,      BR,    IR,     AB,    CB,      CA....]

它应该在下面给我这个输出,因为我想按等级1,等级2,等级3,等级1,等级2,等级3进行打印:

CO IR CB  BR AB CA

但是,当我的代码在第9列发现等于字符串时,我的代码采用第9列的字母顺序。有没有办法检查索引以该顺序显示数据?

这是我的代码:

function readCsv($fileName){

    $handle = fopen($fileName, "r");


    $data=array();

    while ($col = fgetcsv($handle, 1000, ",")) { 

        $data[] = [

            'Section' => $col[0],   
            'Q #' => $col [1],
            'Q Type' => $col[2],
            'Q Title' => $col[3],
            'Q Text' => $col[4],
            'Bonus' => $col [5],
            'Difficulty' => $col[6],
            'Answer' => $col[7],
            'Answer Match' => $col[8],
            'Responses'=> $col[9], 

        ];      

    }

    unset($data[0]); //skip line 1, header
    usort($data, 'cmp');

    fclose($handle);
    return $data;
}
ob_end_flush();



function cmp($a, $b) {

    return $a['Answer Match'] > $b['Answer Match'] (array_search($a['Answer Match'], $a) < array_search($b['Answer Match'], $b)+1);
}

1 个答案:

答案 0 :(得分:0)

您可以分两次使用array_multisort

  1. 首先按“答案匹配”和“回复”进行排序
  2. 在数据中添加新列:一组相同的“答案匹配”值中的序列号
  3. 再次排序,但现在按该新列排序,然后单击“答案匹配”

代码如下:

// Example data
$data = [
    ["Answer Match" => "rank 3", "Responses" => "CB"],
    ["Answer Match" => "rank 1", "Responses" => "CO"],
    ["Answer Match" => "rank 1", "Responses" => "BR"],
    ["Answer Match" => "rank 2", "Responses" => "IR"],
    ["Answer Match" => "rank 2", "Responses" => "AB"],
    ["Answer Match" => "rank 3", "Responses" => "CA"],
];

// First sort by "Answer Match" and then "Responses":
array_multisort(array_column($data, "Answer Match"), 
                array_column($data, "Responses"), SORT_DESC, $data);

// Then add a new column to the data, which gives the sequence number 
// within the same group of "Answer Match":
foreach($data as $i => $a) {
    $data[$i]["i"] = (!$i or $a["Answer Match"] != $data[$i-1]["Answer Match"]) 
                         ? 1 : $data[$i-1]["i"]+1;
}

// Now sort using that extra column to get the final sort order
array_multisort(array_column($data, "i"), array_column($data, "Answer Match"), $data);

// If it bothers you, the extra column can be removed again.