Reputation:
I am reading some JSON data and want to return it as a text from a function. For that, I am doing the following.
<?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);
?>
I can't figure out how to generate a final concatenated string from the function. If I echo
it then it returns what I want but how to capture that output inside a variable. $x.=$x
doesn't help either. I am a beginner in PHP these days.
Upvotes: 1
Views: 133
Reputation: 46630
return
from the function and use concatenation.
...
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);
Upvotes: 2