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条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况