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

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

I need to append the new line character in jsonencode .

My string :-

    $event_details ='';
       foreach($res as $k=>$val){ 
         $event_details  .= "{title:'".$val['event_name']."',";
         $event_details  .= "start:'".$val['start_date']."',";
         $event_details  .= "description:'".$val['event_detail']."'," ;
         $event_details  .= "url:'".$val['event_detail']."'," ;
         $event_details  .= "}," ;
       }

       Now I got  output Like is  
{title:'venuer request event 29-08-2015',start:'2015-09-02',description:'venuer request event
 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
:'singer request event2',start:'2015-08-31',description:'singer request event2',url:'singer
 request event2',}

But I need output like this :

   events: [
        {
            title: 'Event1',
            start: '2015-08-04',
            description :'sample',
            url :'http://localhost.com/melodic_svn/singer/soniya-42',

        },
        {
            title: 'Event2',
            start: '2015-08-25',
            description :'sample1',
            url :'http://localhost.com/melodic_svn/singer/soniya-42'
        }

    ],
  • 写回答

5条回答 默认 最新

  • dragon19720808 2015-08-31 08: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:

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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失