排序多维数组特定元素列

时间:2019-07-18 13:03:17

标签: php sorting multidimensional-array multiple-columns element

我有一个多维数组,由以下示例中显示的8个元素或列组成。 该数组可以来自csv文件或mysql表。 我想从最低到最高对元素2到6进行排序,而不会影响元素1、2和7。 我尝试使用php数组排序函数的变体,但没有任何运气。 有人可以帮忙吗?

var_export view
2 => 
array (
2252 => '2249',
'2019-07-14' => '2019-07-04',
7 => '13',
14 => '18',
27 => '25',
29 => '42',
35 => '43',
'12 ' => '1 ',
),
//------------------------------------------

Tabular view
1   2014-08-03  32  18  12  5   20  2
2   2014-08-03  24  6   23  2   42  14
3   2014-08-03  10  31  11  44  36  8   
//------------------------------------------

    <?php
//  Sort Method #1
function cmp1($a, $b) {
    return strcmp($a["name"], $b["name"]);
}
//usage: usort($vc_array, "cmp1");
//------------------------------------------

//  Sort Method #2
function cmp2($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}
//usage: usort($vc_array, "cmp2");  
//------------------------------------------

//  Process and display
echo "<br><br>";
echo "<table>";
if (($handle = fopen($filename, "r")) == FALSE) {
    echo "error reading csv file";
    exit;
} else {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {   // read csv into array
    $num = count($data);                                    // Count the number of fields in the line
    $info = "<p> $num fields in line $row and each row. </p>";
    echo '<tr>';                                            // Start the new row
    for ($c=0; $c < $num; $c++) {   
        //if (array_key_exists(1,$data)) { $data[1] = date("Y-m-d", strtotime($data[1])); } // reformat date
        echo '<td>';
        echo $data[$c];                                     // display each field
        echo '</td>';
        /*
        if ($c >= 2 or $c <= 6) {
            usort($data[$c], "cmp1");               // attempt at sorting elements 2 to 6
        }
        */
    }
    echo '</tr>';                                           // End of row
    $row++;                                                 // increment row number
    //break;                                                // only show 1 row of data
    }
    echo "</table>";
    echo "<br><br>";
    echo $info;
    echo "<br /><br />";
    fclose($handle);
}
?>

0 个答案:

没有答案