PHP 按在另一个数组中的顺序打印数组值

PHP Print array values in order which is in another array

我有一个数组 ($fields_order_obj),其中包含我想在 table 中打印的列表的名称和顺序索引。 在另一个数组 ($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){
        print "<td>".$row[$obj->name]."</td>\n";
    }
}
print " </tr>\n";

您应该遍历字段数组以保持按预期顺序打印并按字段名称获取行数据。请记住,如果您的数据没有在 $fields_order_obj.

中指定的所有字段,您应该了解情况

这成功了:

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";