2021年3月6日星期六

Shortest way to create JSON in PHP from database fields

In PHP, I want to put some database results as JSON into the options of an HTML's select. Each option will be something like

<option value='{"id":1,"name":"height","type"=2,"value"=0,"unit"="m"}'>height</option>  

The PHP code for this is a mess, because JSON requires double quotes, which PHP uses to parse variables inside strings.

echo '      <option value=\'{"id":'.$row['id'].',"name":"'.$row['name'].'","type":'.$row['type'].',"value":'.$v.',"unit":"'.$row['unit'].'"}\'>'.$row['name']."</option>\n";  

If JSON accepted single quotes, instead of double quotes, this would be simpler:

echo "      <option value=\"{'id':$row[id],'name':'$row[name]','type':$row[type],'value':$v,'unit':'$row[unit]'}\">$row[name]</option>\n";  

An alternative would be to write \" instead of ', but this may be cumbersome.

Is there any easier way to do this?

https://stackoverflow.com/questions/66512536/shortest-way-to-create-json-in-php-from-database-fields March 07, 2021 at 10:01AM

没有评论:

发表评论