我的控制器返回一个多行多列的 PDO 数组。循环浏览我的视图文件中的数据的最佳方法是什么?(或者我应该在模型中做更多的逻辑?)
$user->getDetails(); //returns array in view
foreach($user->getDetails() as $row) // Prehaps? But how to index without being explicit with column names?
谢谢!
视图的重点是运行与视图相关的逻辑和输出结果(即获取数据并根据需要对其进行格式化……如果是 JSON 视图,则输出 JSON。HTML 输出 HTML 等),因此您正在做对的。无论您认为合适,都可以循环遍历它,但是如果没有有关您的数据结构的更多详细信息,我们不能说比您已经想出的更多。
foreach( $user->getDetails() as $row ){
echo $row->name;
echo $row->id;
}
您不需要将 $user->getDetails() 放在顶部,它会调用 foreach 中的函数。
最好的方法或正在使用的方法,在模型中做数据库相关的东西并在视图中格式化布局。在您的情况下,您应该MVC
是将您的编程逻辑保留在控制器中$user->getDetails();
在控制器中调用,然后在视图中传递结果,然后循环它以输出数据,即
在控制器中,您可以使用$user->getDetails()
$user_details=$user->getDetails();
然后$user_details
在加载它并在视图循环中传递给视图
foreach( $user_details as $row ){
echo $row->id;
echo $row->name;
}
如果结果是一个array of arrays
而不是an array of objects
那么你可以使用如下
foreach( $user_details as $row ){
echo $row['d'];
echo $row['name'];
}
更新 :
参考: PHP和This中的模型视图控制器(MVC)。
模型层应该包含所有的业务逻辑。它不应该向控制器返回任何东西。相反,控制器应该只向模型层结构发送消息。
The data from model layer should be extracted by view instance. And depending on nature of data, it would decide which templates to apply.
Views in MVC are supposed to contain all the presentation logic and ( in case of web-related MVC-inspired design patterns) deal with multiple templates. You should also be aware that there exists a 1:1 relation between views and controllers.
If if part of information, that view receives from model layer, is some sort of array, you have two choices. Either you take a template, which can render a single item and repeatedly generate the HTML/JSON/text/XML fragment or you use a template , which expect to receive an array as variable and already contains a loop. The latter approach is usually the more pragmatic one, but each of them as a specific cons an pros.