回答

收藏

PHP并将MySQL行封装到JSON数组中

技术问答 技术问答 302 人阅读 | 0 人回复 | 2023-09-11

我正在玩一个留言簿/聊天室的想法,并且有一个包含三列的MySQL表设置:
: `5 e& l5 t: [/ Z- }1-id-主键自动递增% H% f) z4 W8 G% K8 d
2-名称-字符串5 ]! Z8 b; B! _1 Q; Z  z
3-注释-字符串8 O# Z; y1 `; ~( j
我对PHP的经验很少,但这是我为该操作汇总的内容:
. v2 l: z/ G" ^$result = mysql_query("SELECT * FROM guestbook");
4 O% C# B/ V: ]/ i$i = 0;
% I5 c6 q' b4 C! y  A8 Zwhile($row = mysql_fetch_array($result))
- j! C# F. r8 R5 G) Q  {+ v# q6 L, C: F# r2 t
      //add the row to the $chat array at specific index of $i/ c* O# Z/ n$ V0 q# ?
      $chat[$i] = $row;
# j5 X) z8 q' T+ [: t. G4 @      $i += 1;9 K# r  r* y" i3 q# o
  }/ X5 q* Y7 V+ f1 @& {
$encode = json_encode($chat);
$ k' y- B2 w2 m# secho "$encode";9 [+ j* w9 C. Q+ X; w8 S6 L4 V
但是,此输出看起来很糟糕:& c8 m: `8 R7 l/ e! A  o8 J( B
[{"0":"1","id":"1","1":"Justin ","name":"Justin ","2":"Comment 1","comment":"Comment 1"},
9 O$ [: x4 f; E8 l9 d: S{"0":"2","id":"2","1":"Justin ","name":"Justin ","2":"Another comment","comment":"Another comment"},' m4 y; y8 P5 k5 j
{"0":"3","id":"3","1":"Justin ","name":"Justin ","2":"Look at this comment!","comment":"Look at this comment!"},
3 X! f: C8 N- B- _* f" H) L{"0":"4","id":"4","1":"Justin ","name":"Justin ","2":"Ok I'm done talking","comment":"Ok I'm done talking"}]( s1 \- f: _; d' r' z; j
我希望获得三个字段:ID,名称和注释,但看起来好像翻了一番。有人可以帮忙吗?6 K9 b  z+ @  t+ \, y% |9 y
谢谢!: T5 A2 q. k- O  l( ]" U
               
# c# R5 S% c( O; q2 o& L解决方案:
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则