You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现无表头CSV文件按名称列排序并展示的简单方案

Hey there! Let's get this CSV sorted properly for you—since you're new to PHP, I'll keep this simple and fix both the sorting issue and a tiny bug in your existing code.

Right now, your code reads one row at a time and outputs it immediately, which means there's no chance to sort all the rows first. We need to:

  1. Collect all rows from the CSV into an array first
  2. Sort that array by the name column (the first value in each row)
  3. Then loop through the sorted array to output your table

Also, quick note: Your current code uses $csv_row[1], [2], [3]—but fgetcsv() returns an array starting at index 0. So your name is actually in $csv_row[0], age in [1], city in [2]. The [3] index doesn't exist, which would cause empty output there. I'll fix that too.

Here's the modified, working code:

<?php
// Open the CSV file
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    $all_rows = []; // Empty array to store all CSV rows

    // Read each row and add it to our array
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $all_rows[] = $data; // Add the current row to the array
    }
    fclose($handle);

    // Sort the array by the name column (first element of each row)
    // Use <=> for natural string comparison (works for name1, name2, etc.)
    usort($all_rows, function($a, $b) {
        // For ASCENDING order (name1 → name5)
        return $a[0] <=> $b[0];
        // For DESCENDING order (name5 → name1), replace with:
        // return $b[0] <=> $a[0];
    });

    // Now loop through the sorted rows to output the table
    $i = 1;
    foreach ($all_rows as $csv_row) {
?>
    <tr>
        <td><?php echo $i; ?></td>
        <td><?php echo $csv_row[0]; ?></td> <!-- Fixed index: name is first column -->
        <td><?php echo $csv_row[1]; ?></td> <!-- Age -->
        <td><?php echo $csv_row[2]; ?></td> <!-- City -->
    </tr>
<?php
        $i++;
    }
}
?>

Key parts explained:

  • $all_rows[] = $data: This stores every row from the CSV into a single array, so we can sort all of them at once.
  • usort(): This is PHP's "user-defined sort" function. We pass it our array and a small function that compares the first element (name) of each row. The <=> operator (spaceship operator) does clean string/number comparison, perfect for your name1, name2 pattern.
  • Swapping $a[0] <=> $b[0] to $b[0] <=> $a[0] switches between ascending and descending order—super easy!

When you run this, it'll output exactly the sorted order you wanted:

name1,age18,city2 → name2,age23,city5 → name3,age36,city4 → name4,age44,city1 → name5,age55,city3

内容的提问来源于stack exchange,提问作者N. Josh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:37:19