Php 按数组中的关联列排序csv
我正在尝试按第8列对数组进行排序。列8存储位置1、位置2、位置3等数据。col8必须仅与col7关联,因为col7包含应按col8排序的答案。例如,如果col8=位置1,col7=黄色,col8=位置2,col7=黑色,则应打印黄黑色。 我试图实现我在这里找到的所有示例,但它不起作用Php 按数组中的关联列排序csv,php,arrays,csv,sorting,Php,Arrays,Csv,Sorting,我正在尝试按第8列对数组进行排序。列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
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;
}
应该还黄黑紫
我尝试使用以下代码:
usort($data, function($a, $b) { return strcmp($a["Answer Match"], $b["Answer Match"]); });
但是,它是排序列1,而不是列7
我的输出不正确,因为它打印标题(#Partipant)并按字母顺序排列参与者:
1> 参与者2橙白黑
2> #参与者黑黄紫
正确的输出将是:
1> 参与者1黄黑紫
2> 参与者2橙黑白当您已经拥有所有数据集时,您必须在之后使用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;
}
结果:
听起来您只想对第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;
}
有可能我完全误解了你的问题。那样的话,我道歉
预计到达时间:
数组映射部分过于复杂,没有任何原因;一旦我知道答案是正确的,我会将其改为foreach。什么应该用黄黑打印?有点不清楚…提供csv示例和结果示例(如果您有一个或您可以做一个)@MrSmile它应该打印第一个黄色,因为第8列有位置1。我想按位置排序,而不是按第7列的字母顺序。@MrSmile我把表格包括在上面的问题中。你有多少行?为了确定每一行的位置,您可能需要先遍历所有行,对吗?我的数组有9列95行。出于某种原因,您的解决方案会对第一列而不是第7列和第8列进行排序:(@find83,这很奇怪,因为我已经测试了脚本。看看我编辑的帖子,也许你遗漏了什么。我尝试了你的代码,但它只对第1列排序。我在上面的问题中包含了更多信息。@find83请更新你的完整函数代码。你确定在稍后运行usort吗?我刚刚更新了我的代码。它仍然对C进行排序第1列:(不幸的是,对于您的代码,它只打印第1列。它不是打印第7列和第8列:(您正在打印
$data
?$sortedAnswer
只是一个临时变量,在后记中是无用的。我正在打印$data。在这种情况下如何使用$sortedAnswer
?您不应该使用$sortedAnswer。这只是我的猜测,因为我不明白$data为什么只能有一列;我仍然不明白。我添加了s。)您的一些代码,以确保我们讨论的是相同的数组。