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

如何为simple_html_dom解析的HTML表格添加双列自定义排序功能

Solution for Sorting Parsed HTML Table with Dual Priorities

Got it, let's tackle this sorting task for your table parsed via simple_html_dom. We'll break this down into manageable steps: converting parsed rows into a sortable format, applying your custom priority rules, then rebuilding the sorted table. Here's the full breakdown:

Step 1: Extract Table Data from simple_html_dom

First, we'll load your HTML, grab the table, and separate the header (which we don't want to sort) from the data rows. We'll store both the cell values and original DOM elements to preserve any existing styling:

// Load your HTML source (replace with your actual content)
$html = str_get_html($your_html_content);
$targetTable = $html->find('table', 0); // Grab the first table on the page

// Extract header row (skip if your table doesn't use <thead>)
$headerRow = $targetTable->find('thead tr', 0) ?? $targetTable->find('tr', 0);

// Collect data rows (skip the header row)
$tableRows = [];
foreach ($targetTable->find('tr') as $index => $row) {
    if ($index === 0) continue; // Skip header
    
    $cellValues = [];
    foreach ($row->find('td') as $cell) {
        $cellValues[] = trim($cell->plaintext);
    }
    
    $tableRows[] = [
        'values' => $cellValues,
        'original_row' => $row // Keep original DOM to preserve styling/attributes
    ];
}

Step 2: Apply Custom Sorting Logic

We'll use PHP's usort() with a custom comparator to enforce your two priority rules. First, define a weight map for the position column, then compare rows:

// Define position priority mapping (matches your required order)
$positionWeight = [
    'PG' => 1,
    'SG' => 2,
    'SF' => 3,
    'PF' => 4,
    'C' => 5
];

// Sort the rows
usort($tableRows, function($rowA, $rowB) use ($positionWeight) {
    // 1st Priority: Sort by position
    $posA = $rowA['values'][0]; // Adjust index if "pos" isn't the first column!
    $posB = $rowB['values'][0];
    
    // Get weights (push unknown positions to the end with a fallback value)
    $weightA = $positionWeight[$posA] ?? 6;
    $weightB = $positionWeight[$posB] ?? 6;
    
    if ($weightA !== $weightB) {
        return $weightA - $weightB; // Ascending order per your rules
    }
    
    // 2nd Priority: Sort by 2ga (numeric value)
    $gaA = intval($rowA['values'][3]); // Adjust index if "2ga" isn't the 4th column!
    $gaB = intval($rowB['values'][3]);
    
    // Use $gaA - $gaB for ascending, $gaB - $gaA for descending
    return $gaB - $gaA;
});

Important Check: Double-check the column indexes for pos and 2ga! If pos is the 2nd column, use index 1 instead of 0, and adjust the 2ga index to match your table's structure.

Step 3: Rebuild the Sorted Table

Now we'll reconstruct the HTML table using the original header and sorted rows. We can reuse the original DOM rows to keep any existing styling, or rebuild cells from scratch if you modified values:

// Start building the sorted table HTML
$sortedTableHTML = '<table>' . PHP_EOL;

// Add the header row
$sortedTableHTML .= '<tr>' . PHP_EOL;
foreach ($headerRow->find('th') as $headerCell) {
    $sortedTableHTML .= '<th>' . htmlspecialchars($headerCell->plaintext) . '</th>' . PHP_EOL;
}
$sortedTableHTML .= '</tr>' . PHP_EOL;

// Add sorted data rows
foreach ($tableRows as $row) {
    // Option 1: Reuse original row to preserve styling/attributes
    $sortedTableHTML .= $row['original_row']->outertext . PHP_EOL;
    
    // Option 2: Rebuild row from modified values (uncomment if needed)
    // $sortedTableHTML .= '<tr>' . PHP_EOL;
    // foreach ($row['values'] as $cellValue) {
    //     $sortedTableHTML .= '<td>' . htmlspecialchars($cellValue) . '</td>' . PHP_EOL;
    // }
    // $sortedTableHTML .= '</tr>' . PHP_EOL;
}

$sortedTableHTML .= '</table>';

// Output or save the sorted table
echo $sortedTableHTML;

// Clean up simple_html_dom resources
$html->clear();
unset($html);

Quick Notes

  • Unknown Positions: The fallback value 6 pushes any unrecognized position labels to the end of the sorted list—adjust this if you want a different behavior.
  • 2ga Value Handling: Using intval() ensures we treat cell content as a number, even if there's extra whitespace. If your 2ga cells might have non-numeric content, add a check like is_numeric() first to avoid unexpected sorting.
  • Styling Preservation: Storing the original original_row DOM element lets you keep any classes, inline styles, or attributes from the original table, which is handy if you don't want to lose formatting.

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:58:15