我有一个数组($fields_order_obj),其中包含我想在表中打印的列表的名称和orderindex。在另一个数组($data)中,我有我想要打印的所有值,但顺序与$fields_order_obj数组中的顺序不同。我用fetchmode ADODB_FETCH_ASSOC的查询从SQL中取出这个数组我用foreach ($data as $row){}遍历每一行
$fields_order_obj ([name] => Del_Month [size] => 10 [reportindex] => 0, [name] => Del_Date [size] => 10 [reportindex] => 1, [name] => Article [size] => 10 [reportindex] => 3, ect.)
$data [0]([name] => Article [value] => "A", [name] => Del_Date [value] => "03-03-21", [name] => Del_Month [value] => "March"),[1]([name] => Article [value] => "B", [name] => Del_Date [value] => "01-02-21", [name] => Del_Month [value] => "Feb"), ect.
目前为止我有什么:
print "<table style="width:100%">";
print " <tr>n";
foreach ($fields_order_obj as $obj){
print "<th>".$obj->name."</th>n";
}
print " </tr>n";
foreach ($data as $row) {
print " <tr>n";
foreach ($row as $name => $value) {
print "<td>".$value."</td>n";
}
}
print " </tr>n";
显然数据没有按我想要的顺序打印,我需要检查和比较字段的name
,然后检查reportindex
以正确的顺序打印,但我似乎无法编写正确的代码…
成功了:
print "<table style="width:100%">";
print " <tr>n";
foreach ($fields_order_obj as $obj){
print "<th>".$obj->name."</th>n";
}
print " </tr>n";
foreach ($data as $row) {
print " <tr>n";
foreach ($fields_order_obj as $obj){
$fieldName = $obj->name;
print "<td>".$row[$fieldName]."</td>n";
}
}
print " </tr>n";
我想你的代码应该是这样的:
print "<table style="width:100%">";
print " <tr>n";
foreach ($fields_order_obj as $obj){
print "<th>".$obj->name."</th>n";
}
print " </tr>n";
foreach ($data as $row) {
print " <tr>n";
foreach ($fields_order_obj as $obj){
print "<td>".$row[$obj->name]."</td>n";
}
}
print " </tr>n";
您应该遍历字段数组以保持按预期顺序打印,并按字段名获取行数据。请记住,如果您的数据没有$fields_order_obj
中指定的所有字段,您应该意识到这种情况。