doucheng4094 2015-08-31 00:10
浏览 53
已采纳

如何在php json响应中追加新行字符

I need to append the new line character in jsonencode .

My string :-

  1. $event_details ='';
  2. foreach($res as $k=>$val){
  3. $event_details .= "{title:'".$val['event_name']."',";
  4. $event_details .= "start:'".$val['start_date']."',";
  5. $event_details .= "description:'".$val['event_detail']."'," ;
  6. $event_details .= "url:'".$val['event_detail']."'," ;
  7. $event_details .= "}," ;
  8. }
  9. Now I got output Like is
  10. {title:'venuer request event 29-08-2015',start:'2015-09-02',description:'venuer request event
  11. 29-08-2015',url:'venuer request event 29-08-2015',},{title:'test event2',start:'2015-08-31',description:'test events1',url:'test events1', },{title:'venuer request event2',start:'2015-08-31',description:'venuer request event2',url:'venuer request event2',},{title
  12. :'singer request event2',start:'2015-08-31',description:'singer request event2',url:'singer
  13. request event2',}

But I need output like this :

  1. events: [
  2. {
  3. title: 'Event1',
  4. start: '2015-08-04',
  5. description :'sample',
  6. url :'http://localhost.com/melodic_svn/singer/soniya-42',
  7. },
  8. {
  9. title: 'Event2',
  10. start: '2015-08-25',
  11. description :'sample1',
  12. url :'http://localhost.com/melodic_svn/singer/soniya-42'
  13. }
  14. ],

展开全部

  • 写回答

5条回答 默认 最新

  • dragon19720808 2015-08-31 00:20
    关注

    PHP got a neat little function called json_encode. Now, you don't want to add your current string to the json_encode function, but rather a object or array instead. Why? Well, cause you really don't want to manually put json strings together like that.
    Instead of creating a string in the for-each loop, all you have to do is add the properties to an array and then pass it to the json_encode function and use the JSON_PRETTY_PRINT flag.

    Example:

    1. $event_details = array();
    2. foreach($res as $event){
    3. $eventArray = [
    4. 'title' => $event['event_name'],
    5. 'start' => $event['start_date'],
    6. ... And so on ...
    7. ];
    8. array_push($event_details, $eventArray);
    9. }
    10. $json = json_encode($event_details, JSON_PRETTY_PRINT);
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部