foreach循环仅返回数组中的一项 [英] foreach loop returns only one item from the array

查看:67
本文介绍了foreach循环仅返回数组中的一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环遍历的数组,每个循环仅返回第一次迭代,但是如果我将其更改为回显,则会将所有这些迭代打印到屏幕上,这是PHP的新手,不知道为什么会这样尝试寻求答案,但没有找到答案.下面的代码:

I have an array that I loop through with for each loop it returns only the first iteration but if I change it to echo it prints all of them to the screen, new to PHP not sure why is it acting this way tried looking for an answer but did not find one. the code below:

    function getData($values){
        foreach ($values as $key => $value){
            return "<p>". $key . " " . $value ."</p></br>";

        }

    }

    $SubmitedResult->SerialisedForm = getData($data);

推荐答案

return 总是退出该函数并返回其参数.从文档:

如果从函数内部调用,则return语句立即终止当前函数的执行,并将其参数作为函数调用的值返回.

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.

如果您不希望发生这种情况,请尝试附加到变量,并在完成附加后将其返回:

If you don't want this to happen, try appending to a variable, and returning it when you've finished appending:

function getData ($values) {
    $form = '';
    foreach ($values as $key => $value) {
        $form .= "<p>". $key . " " . $value ."</p></br>";
    }
    return $form;
}

这篇关于foreach循环仅返回数组中的一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆