douwen7905 2012-08-26 14:43
浏览 100
已采纳

如何使用PHP从foreach循环返回多个值

Here's my function

function GetUser($id)
{
    global $pdo;
    $stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
    $stmt->execute(array(':id'=>$id));
    foreach($stmt as $name){
        $lname = $name['lname'];
        $lname = $name['fname'];
        $mi = $name['mi'];
    }

    return //what to put here?
}

Here's my code to use the function

include 'function.php';
$names = GetUser($_SESSION['id']);
//what's next?

How can i retrieve the $lname,$fname and $mi from the function? Need any help and suggestions. Thank you :)

  • 写回答

5条回答 默认 最新

  • doujianqin5172 2012-08-26 14:47
    关注

    For starters don't use the global keyword, but inject the variable you need. Second why don't you return an array?:

    function getUser($pdo, $id)
    {
        $stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
        $stmt->execute(array(':id'=>$id));
    
        $result = array();
        foreach($stmt as $name){
            $result['lname'] = $name['lname'];
            $result['fname'] = $name['fname'];
            $result['mi']  = $name['mi'];
        }
    
        return $result;
    }
    
    $result = getUser($pdo, 1);
    var_dump($result);
    

    Note that this will only return the last result. If you want it all:

    function getUser($pdo, $id)
    {
        $stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
        $stmt->execute(array(':id'=>$id));
    
        return $stmt->fetchAll();
    }
    
    $result = getUser($pdo, 1);
    var_dump($result);
    

    Also note that I have made your function name starting with a normal letter instead of a capital. The "normal" naming convention is that classes start with a capital, but function / methods with a normal one.

    If you want to retrieve the information based on the first solution you would do:

    echo $result['lname'];
    

    If you want to retrieve the information based on the second solution you would do:

    echo $result[0]['lname'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器