如何将数据编码为json?

我想将数据编码为json。现在,通过底部代码,我具有ID和产品标题,但是我想添加其他数据,例如费用。我怎样才能做到这一点?


<?php


$sql = 'SELECT id,title,cost,cat

        FROM prodcts_df';

$q = $db->query($sql);

$q->setFetchMode(PDO::FETCH_ASSOC);


?>


 <?php

 while ($r = $q->fetch()): ?>

    <?php $myJson->$r['id']= $r['title'];?>

 <?php endwhile; ?>


<?php echo json_encode($myJson); ?>


慕容3067478
浏览 118回答 3
3回答

大话西游666

您可以像这样在json_encode之前在数组中添加成本:&nbsp;// ......&nbsp;while ($r = $q->fetch()) {&nbsp;&nbsp; &nbsp; $myJson->$r['id']= [&nbsp; &nbsp; &nbsp; &nbsp;'title' => $r['title'],&nbsp; &nbsp; &nbsp; &nbsp;'cost'&nbsp; => $r['cost'],&nbsp; &nbsp; &nbsp; &nbsp;//.....&nbsp; &nbsp; ];&nbsp;}// .....

梵蒂冈之花

您最好将整个行($r)添加到数组中,而不仅仅是标题。您还应该$myJson首先初始化数组()...$sql = 'SELECT id,title,cost,cat&nbsp; &nbsp; &nbsp; &nbsp; FROM prodcts_df';$q = $db->query($sql);$q->setFetchMode(PDO::FETCH_ASSOC);// Initialise array$myJson = []while ($r = $q->fetch()) {&nbsp; &nbsp; // Add the row to the array indexed by the ID&nbsp; &nbsp; $myJson[$r['id']]= $r;}echo json_encode($myJson);请注意,我使用$myJson[$r['id']]而不是$myJson->$r['id']添加它,在索引这样的数据列表时更常见。如果您只想要阵列的一部分...$myJson[$r['id']]= [ 'title' => $r['title'], 'cost' => $r['cost']];

SMILET

json_encode($myJson);会将您的对象编码为JSON。如果将其他数据添加到$ myJson变量中,它将在输出中包括这些数据:$myJson['foo']&nbsp;=&nbsp;'bar';
打开App,查看更多内容
随时随地看视频慕课网APP