为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
精慕HU 2024-01-19 17:18:06
我正在读取一些 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 的初学者。
查看完整描述

1 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

return从函数和使用串联。


...

function rex($json){

  $x = '';

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

    $x .= '

    <tr>

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

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

    </tr>';

  }

  return $x;  

}

    

echo rex($json1);


查看完整回答
反对 回复 2024-01-19
  • 1 回答
  • 0 关注
  • 30 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信