如何使用PHP更改子数组值的顺序以创建表?

时间:2014-07-07 20:24:11

标签: php arrays html-table

我有以下代码,可以根据这里讨论的子数组的值创建一个表:Creating a table with values of a subquery in PHP

<?php

$array = array(
    "0" => array("1", "2", "3", "4", "5"),
    "1" => array("I", "II", "III", "IV", "V"),
    "2" => array("i", "ii", "iii", "iv", "v"),
    "3" => array("A", "B", "C", "D", "E"),
    "9" => array("a", "b", "c", "d", "f")
);

print_r($array);

    $table = '<table border=1>';
    // Select values of the array to create table.
    foreach($array as $key => $row){
        $table .= '<tr>';
        foreach($row as $value){
            $table .= '
                    <td>'.$value.'</td>
            ';
        }
        $table .= '</tr>';
    }
    $table .= '</table>';

    echo $table;
?>

表格如下:

| 1 | 2 | 3 | 4 | 5 |
...
| A | B | C | D | E |
| a | b | c | d | e |
etc.

但是,如果我想排除某些值并将其他值放在另一个顺序中,我可以做什么呢?

| 3 | 4 | 5 | 2 |
| C | D | E | B |
| c | d | e | b |
etc.

换句话说,我要做的是排除第一个值并将第二个值放在表格的最后一个单元格中?

2 个答案:

答案 0 :(得分:2)

您可以使用单独的数组来跟踪要显示的列,并按照您想要的顺序保留该数组。

$array = array(
  "0" => array("1", "2", "3", "4", "5"),
  "1" => array("I", "II", "III", "IV", "V"),
  "2" => array("i", "ii", "iii", "iv", "v"),
  "3" => array("A", "B", "C", "D", "E"),
  "9" => array("a", "b", "c", "d", "f")
);
$column_order = array(2,3,4,1);
//indexes are 0 based, so column "2" is going to be "C" for example
$table = '<table border=1>';
// Select values of the array to create table.
foreach($array as $key => $row){
    $table .= '<tr>';
    foreach($column_order as $index){
        $table .= '
                <td>'.(array_key_exists($index, $row) ? $row[$index] : '').'</td>
        ';
    }
    $table .= '</tr>';
}
$table .= '</table>';

答案 1 :(得分:0)

我将在前言中说,没有一个好方法可以做你所要求的。您应该创建一个索引顺序并遵循它。

忽略列很简单,只需检查是否要忽略该键......

通过交换子阵列可以更好地实现将列移动到最后,但可以通过滥用迭代来完成。

$table = '<table border=1>';
// Select values of the array to create table.
for($i = 0; $i < count($array); $i++){
    $table .= '<tr>';
    for($j = 0; $j < count($array[$i]) + 1; $j++)
    {            
        if($j > 1) // Skip first and second columns
             $table .= '
                    <td>'.$array[$i][$j].'</td>
            ';
        else if($j == count($array[$i]))  //if past the alst column
             $table .= '
                    <td>'.$array[$i][1].'</td> //Use Second column
            ';
    }
    $table .= '</tr>';
}
$table .= '</table>';