在 PHP 中循环从 MySQL 查询返回的数组
我有一个应用程序的一部分,它以数组的形式循环返回 MySQL 查询(众所周知)。但是,我需要对某些返回的项目进行几种不同的格式设置,例如,一列需要日元,另一列需要美国货币,而返回的项目之一是图像的链接。
我将使用列的名称,但是我用来完成此操作的相同函数将用于许多不同的表。
这就是到目前为止我所拥有的循环。
while($row = mysql_fetch_array($result)) {
for($i=0;$i<=count($row);$i++) {
if($row[i]==$row['Yen_Price']) {// I didn't expect this to work...but this is what I would like to do.
echo "Hello";
}
echo "<td>" . $row[$i] . "</td>";
}
}
I have a part of an application that loops through a return of a MySQL query (as we all know) in the form of an Array. However, I need several different format settings placed on some of the items returned, for example, one column needs Japanese currency, the other has American currency and one of the returned items is a link to an image.
I would use the names of the column, however this same function that I am using to accomplish this will be used for many different tables.
This is what I have for the loop so far.
while($row = mysql_fetch_array($result)) {
for($i=0;$i<=count($row);$i++) {
if($row[i]==$row['Yen_Price']) {// I didn't expect this to work...but this is what I would like to do.
echo "Hello";
}
echo "<td>" . $row[$i] . "</td>";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
话虽如此,使用相同的函数来处理所有可能表中的所有结果很快就会变得相当难以管理。您应该自定义它以适应场合,如下所示:
Having said that, using the same function to process all results from all possible tables will soon be rather unmanageable. You should customized this to fit the occasion like so:
我会针对每个表标记这些结果,但如果您希望它最终变得灵活,请尝试这个臭代码
请注意,这是一个 已知的反模式,你真的应该考虑另一种方法来解决这个问题。
I'd markup these results specific to each table but if you want it to be ultimately flexible, try this smelly code
Note that this is a known antipattern and you should really think about another way to approach the problem.
使用以下代码。您可以根据需要进行修改。
谢谢
Use the below code. You can modify it as you want.
Thanks
在我成为框架狂热者之前,我曾经采用过一些不同的方法。我的数据库库有一组方法可以返回记录集数组。这样我就可以将数据库交互与使用记录集的方式完全分开。完成此操作后,可以轻松设置网格模板,该模板可以查看数组,然后采取相应的操作。这是一些伪代码
Before I became a framework fanatic I used to have a bit different approach. My db library had set of methods that returned me array of record sets. This way I keep my db interaction totally separate from how I consume the record sets. Having done this, its easy to set up a grid template which can look at array and then act accordingly. Here is some pseudo code