douyan8961 2016-12-10 11:19
浏览 63
已采纳

在php中将对象转换为JSON的问题

I need to convert an object into JSON using a php script.

I wrote this code in a loop cycle:

$zaino->rows[$num_oggetti]->item = $oggetto;
$zaino->rows[$num_oggetti]->amount = $num;

After the loop cycle I convert the object into json: json_encode($zaino);

This is what I get:

{"rows":{"1":{"item":"Soffio di Morte","amount":"1"},"2":{"item":"Pietra Anima di Ferro","amount":"11"},"3":{"item":"Pietra Anima di Legno","amount":"12"}}

But I need something like:

{"rows":[{"item":"Soffio di Morte","amount":"1"},{"item":"Pietra Anima di Ferro","amount":"11"},{"item":"Pietra Anima di Legno","amount":"12"}]}

without numbers between "", so that I can easily get the values using for example $zaino->rows[1]->item after calling a json_decode. How can I do it?

  • 写回答

1条回答 默认 最新

  • doushishi2415 2016-12-10 12:49
    关注

    The problem is that $num_oggetti is a string value, not a number (yes, numeric, but not a number). This tells PHP that you are setting a key instead of an index.

    If you do not need the actual index you could do something like:

    $zaino->rows[] = [
      'item'   => $oggetto,
      'amount' => $num
    ];
    

    This way you leave the index generation entirely up to PHP and you'll get the json output you want.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!