如何在 PHP 循环中递归连接字符串

我正在读取一些 JSON 数据,并希望将其作为文本从函数返回。为此,我正在做以下事情。


<?php


    $json = '{"Business":["Accounting","Macroeconomics"],"0":["English","English","Other","Penmanship"],"Math":["Calculus","Fractions","Functions"],"Other":["Geography","Philosophy"],"Science":["Geology","Physical Science"]}';

    

    $json1 = json_decode($json, true);

    

    

    function rex($json){

        

        foreach ($json as $key=>$value){

            $x='<tr>

                <td style="width:30%;font-weight:700;padding-bottom:10px">'.$key.'</td>

                <td>'.implode(' ,',$value).'</td>

               </tr>';

           echo $x;

        }

    }

    

    rex($json1);

    

    ?>

我不知道如何从函数生成最终的连接字符串。如果我echo这样做,那么它会返回我想要的内容,但如何在变量内捕获该输出。$x.=$x也没有帮助。这些天我是 PHP 的初学者。


精慕HU
浏览 36回答 1
1回答

12345678_0001

return从函数和使用串联。...function rex($json){&nbsp; $x = '';&nbsp; foreach ($json as $key => $value) {&nbsp; &nbsp; $x .= '&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td style="width:30%;font-weight:700;padding-bottom:10px">'.$key.'</td>&nbsp; &nbsp; &nbsp; <td>'.implode(', ',$value).'</td>&nbsp; &nbsp; </tr>';&nbsp; }&nbsp; return $x;&nbsp;&nbsp;}&nbsp; &nbsp;&nbsp;echo rex($json1);
打开App,查看更多内容
随时随地看视频慕课网APP