"Properly" 遍历(我的)SQL 响应
"Properly" looping through (my)SQL response
我有一个 class 可以为我做 MySQL 的事情。
我在 MySQL Table 中有 1 到 n 行,想查询特定结果。
要查询 table,我现在可以使用
$db->select('tablename', '*');
$res = $db->Result()
以关联数组形式获取结果。
现在如果我想遍历,我必须检查是否有一个或多个结果,然后显示那个结果或循环遍历结果。
这会使我的代码膨胀,我想找到一种方法来合并这两个结果。
目前,我正在这样做:
if(is_array($res[0]){
//we have more than one result
foreach($res as $something)
{
//do stuff here
}
}
else
{
//do the same stuff as above here but now with other variables since $something is only filled in the foreach loop
}
现在如前所述,我很乐意将这两者结合起来,并且只有一段代码来显示结果(或进一步使用它们)
将输入数据结构更改为循环期望的格式,然后在循环中对其进行迭代:
if(!is_array($res[0]){
$res[0] = [$res[0]];
}
foreach($res as $something)
{
//do stuff here
}
我建议您切换到一些广泛开发的 类,例如 PDO (http://php.net/manual/en/book.pdo.php),或者只是在您的 Result
方法中添加一个 returns 空的检查没有结果的数组
function Result() {
// stuff to fetch and fill $arr;
return (is_array($arr[0])) $arr : array();
}
我有一个 class 可以为我做 MySQL 的事情。 我在 MySQL Table 中有 1 到 n 行,想查询特定结果。
要查询 table,我现在可以使用
$db->select('tablename', '*');
$res = $db->Result()
以关联数组形式获取结果。
现在如果我想遍历,我必须检查是否有一个或多个结果,然后显示那个结果或循环遍历结果。
这会使我的代码膨胀,我想找到一种方法来合并这两个结果。
目前,我正在这样做:
if(is_array($res[0]){
//we have more than one result
foreach($res as $something)
{
//do stuff here
}
}
else
{
//do the same stuff as above here but now with other variables since $something is only filled in the foreach loop
}
现在如前所述,我很乐意将这两者结合起来,并且只有一段代码来显示结果(或进一步使用它们)
将输入数据结构更改为循环期望的格式,然后在循环中对其进行迭代:
if(!is_array($res[0]){
$res[0] = [$res[0]];
}
foreach($res as $something)
{
//do stuff here
}
我建议您切换到一些广泛开发的 类,例如 PDO (http://php.net/manual/en/book.pdo.php),或者只是在您的 Result
方法中添加一个 returns 空的检查没有结果的数组
function Result() {
// stuff to fetch and fill $arr;
return (is_array($arr[0])) $arr : array();
}