简体   繁体   English

动态表迭代PHP MySql

[英]Dynamic Table Iteration PHP MySql

Suppose I have an SQL Statement that looks like: 假设我有一个看起来像这样的SQL语句:

SELECT * FROM myTable;

Now back in PHP I have a result array $result[], How can I iterate through that array and print out the values if I don't know the column names? 现在回到PHP中,我有一个结果数组$ result [],如果不知道列名,如何遍历该数组并打印出值? Can I interrogate the array somehow? 我可以以某种方式询问阵列吗?

Background: I have a table, I've rendered the table headings based on the a metadata table, now I need to populate the data, but I only want to pull out the field names that match the table headers and insert them into the HTML Table. 背景:我有一个表,我已经基于元数据表渲染了表标题,现在我需要填充数据,但是我只想提取与表头匹配的字段名称并将其插入HTML表。

This process is happening dynamically, every table is different and has different field names (discovered by interrogating the metadata), but shares the same php code, so it needs to be flexible and smart enough to figure out what to render. 这个过程是动态发生的,每个表都是不同的,并且具有不同的字段名(通过查询元数据来发现),但是共享相同的php代码,因此它需要足够灵活和智能以找出要呈现的内容。

Edit: I now understand that your $result is an array of arrays . 编辑:我现在知道您的$ result是arrays的数组

foreach ($result as $row) {
    foreach ($row as $key => $value) {
      print "column $key has value $value\n";
    }
}

Or you can call array_keys($row) to return the keys of an associative array. 或者,您可以调用array_keys($ row)返回关联数组的键。

You can use foreach loop with key-value pair in that case. 在这种情况下,可以将foreach循环与键值对结合使用。

You can use it like this, 你可以这样使用

foreach($result as $key=>$value) {
    //$key returns the key of $result array
    //$value returns the respective value of that key
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM