如何更改子阵值以创建使用PHP表? [英] How to change order of subarray values to create a table using PHP?

查看:168
本文介绍了如何更改子阵值以创建使用PHP表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下code创建从子阵列的值的表作为这里讨论:创建的表的值在PHP中的子查询

I have following code that creates a table from the values of the subarrays as discussed here: 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.

但我能怎么办呢,如果我想排除一些价值观和让别人在另一为了就像下面?

But what could I do, if I like to exclude some values and have others in another order just like the following?

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

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

In another words what I have to do to exclude the first value and put the second in the last cell of the table?

在事先非常感谢!

推荐答案

您可以使用一个单独的数组跟踪哪些栏,显示,并保持在您想要的顺序排列。

You can use a seperate array to keep track of which column to show, and keep that array in the order you want.

$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>';

这篇关于如何更改子阵值以创建使用PHP表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆