php函数以数组形式返回包含数组的sql结果

标签 php mysql arrays foreach

所以我遇到了问题(很明显)。我有以下MySQL表数据

7   USER1       1,1,1,10,1      The Guys Team   8,7,13,14,16
8    USER1      1,1,1,10,1  The Girls Team  7,12,15
10  USER1       1,1,1,10,1  Dog Team    8,7,14,15

我编写了一个函数来检索数据并将其返回。

function ShowSetTeams($coach){
    $result = mysql_query("SELECT * FROM `teams` WHERE coach = '$coach'") or trigger_error(mysql_error()); 
    while($row = mysql_fetch_array($result)){ 
        foreach($row AS $key => $value) { $row[$key] = stripslashes($value); } 
            $id = $row['id'];
            $teamname = $row['teamname'];
            $team = $row['team'];
            $event = $row['event'];
            $push .= array($id, $teamname, $team, $event);
    }
    return $push;
}

当我调用函数时,如下所示

$info = ShowSetTeams("USER1");

我明白了

ArrayArrayArray 

我尝试回显 $info[0]、$info[1] 和 $info[2],但得到了这个

Arr

所以信息数组中的每一行都是结果数组。我应该能够执行 $info[0][0] 并从第一个结果中获取第一个 ID 值,对吗?

Fatal error: Cannot use string offset as an array

我很茫然。 我如何获得返回数组的每个值?更重要的是,我如何对它们运行 foreach 操作,例如

foreach( $info as $key => $value){
$key[0] //ID
$key[1] //TEAMNAME
$key[2] //TEAM
$key[3] //EVENT
}

最佳答案

您正在使用字符串连接而不是数组表示法:

$push[] = array($id, $teamname, $team, $event);

在开始使用之前,您还应该初始化 $push = array();

你还做了很多额外的工作......你可以这样做:

function ShowSetTeams($coach)
{   
    $push = array();
    $result = mysql_query("SELECT id, teamname, team, event FROM `teams` WHERE coach = '$coach'") or trigger_error(mysql_error());
    while($row = mysql_fetch_array($result, MYSQL_NUM))
    {
        // I doubt you actually need to run stripslashes on your data...
        $row = array_map('stripslashes', $row);
        $push[] = $row;
    }

    return $push;
}

除非您必须这样做,否则我也不会使用将其重新键入到数字索引数组 - 您只会让您在以后的代码中更难理解。使用 mysql_fetch_assoc()做这个

关于php函数以数组形式返回包含数组的sql结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1553279/

相关文章:

php - 遍历 $_POST 并添加到数据库

php - 如何在 Guzzle 中设置引用 header

mysql - 如何在Apache Kafka中访问远程数据库?

PHP 总是正确插入数据,但一旦失败并插入重复数据?

mysql - 有什么方法可以替换 SELECT * FROM `INFORMATION_SCHEMA` 查询吗?

c++ - 自动售货机项目

javascript - 将 2 个值分配给整个键数组

php - Laravel 5 - Controller 中的路由和可变参数

ios - 我将如何设置 AnyObject.Type 对象数组?

php - PHP的优缺点?