按数组csv

时间:2018-07-14 17:41:02

标签: php arrays csv sorting

我正在尝试按第八列对数组进行排序。列8存储了位置1,位置2,位置3等数据。col8仅与col7相关联,因为col7保留应由col8排序的答案。例如,如果col8 =位置1和col7 =黄色,col8 =位置2和col7 =黑色,则应将黄色打印为黑色。 我尝试实现在此找到的所有示例,但是没有用。

    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], 

        ]; 

    }

   usort($data, function($a, $b) { return strcmp($a["Answer Match"], $b["Answer Match"]); });


    fclose($handle);
    return $data;
}

enter image description here

应返回黄色黑色紫色。

我尝试使用以下代码:

usort($data, function($a, $b) { return strcmp($a["Answer Match"], $b["Answer Match"]); });

但是,它正在对第1列而不是对Colum 7进行排序。

enter image description here

我的输出给出了错误的信息,因为它打印了标题(#参与者)并将参与者按字母顺序排列:

1>参与者2橙色白色黑色 2>#参与者黑色黄色紫色

正确的输出将是:

1>参与者1黄色黑色紫色

2>参与者2橙色黑色白色

2 个答案:

答案 0 :(得分:0)

在拥有所有数据集后,必须在 之后使用usort。而且您的比较功能不好,请看这里:

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],

    ];
}
usort($data, function($a, $b) { return strcmp($a["Answer Match"], $b["Answer Match"]); });
fclose($handle);
return $data;
}

结果:

enter image description here

答案 1 :(得分:0)

听起来您只想对第7列和第8列进行排序;而您想保留第1 ... 6,9列的“未排序” /左侧。在数组的上下文中这有点奇怪,因此需要一些解决方法:

//Your code for context
function readCsv($fileName){
$handle = fopen($fileName, "r");
$data=array();
while ($col = fgetcsv($handle, 1000, ",")) { 
    $data[] = //removed
}

//take columns 7 and 8 out, and sort them separately.
$sortedAnswer = array_column($data,'Answer','Answer Match');
ksort($sortedAnswer);
reset($sortedAnswer);

//pluck the columns back in.
$data = array_map(function($v) use (&$sortedAnswer) {
  $v['Answer'] = current($sortedAnswer);
  $v['Answer Match'] = key($sortedAnswer);
  next($sortedAnswer);
  return $v;
}, $data);
unset($sortedAnswer);

//your code for context
fclose($handle);
return $data;
}

我可能完全误解了您的问题。在这种情况下,我表示歉意。

ETA: array_map部分过于复杂,没有任何原因。一旦知道答案正确后,我便将其更改为foreach。