duan0514324
2014-08-23 18:09 阅读 35

如何在PHP中将键值添加到已解码的json中?

I use youtube gdata to get video links. PHP code I use:

$json_output = json_decode($json,TRUE);
foreach ( $json_output['data']['items'] as $data ){

echo $data['title']
. '</br>' 
. $data['content'][1]
. '</br>';

The url is http://gdata.youtube.com/feeds/api/videos?q=whatever&v=2&max-results=5&format=1&alt=jsonc. This gives me the following output:

 Best of whatever 2013
rtsp://r3---sn-o097zuee.c.youtube.com/CiILENy73wIaGQmMKLazIS6kpRMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
2 Girls Asking For 3somes
rtsp://r4---sn-o097zuek.c.youtube.com/CiILENy73wIaGQlmFTJbhKvUOhMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
Girl Picking Up Girls
rtsp://r8---sn-o097zuer.c.youtube.com/CiILENy73wIaGQk1tOjZuJyf2RMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
Awkward Track Situations
rtsp://r8---sn-o097zuek.c.youtube.com/CiILENy73wIaGQkYo23fr3XTdRMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
Asking 200 Girls For Sex (Social Experiment)
rtsp://r8---sn-o097zued.c.youtube.com/CiILENy73wIaGQlzWxK8A722IhMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp

Now I want something like below:

Best of whatever 2013
rtsp://r3---sn-o097zuee.c.youtube.com/CiILENy73wIaGQmMKLazIS6kpRMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
[---I want a name here---]
2 Girls Asking For 3somes
rtsp://r4---sn-o097zuek.c.youtube.com/CiILENy73wIaGQlmFTJbhKvUOhMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
[---I want a name here---]
Girl Picking Up Girls
rtsp://r8---sn-o097zuer.c.youtube.com/CiILENy73wIaGQk1tOjZuJyf2RMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
[---I want a name here---]
Awkward Track Situations
rtsp://r8---sn-o097zuek.c.youtube.com/CiILENy73wIaGQkYo23fr3XTdRMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
[---I want a name here---]
Asking 200 Girls For Sex (Social Experiment)
rtsp://r8---sn-o097zued.c.youtube.com/CiILENy73wIaGQlzWxK8A722IhMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
[---I want a name here---]

The names are indexed array like:

Names=Red, Green, You, Me.....

How to perform this? I used array_push or merge functions, but it adds only an array, not a variable like Title or Content.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douji5397 douji5397 2014-08-23 18:27

    Have a counter outside the foreach like $count = 0; then inside the foreach do $count++;. You can then get the name corresponding to the item using $names[$count]; inside the foreach.

    $json_output = json_decode($json,TRUE);
    $count = 0;
    $names = ['name1', 'name2', 'name3', 'name4'];
    foreach ( $json_output['data']['items'] as $data ){
         echo ($data['title'] . '<br />' . $data['content'][1] . '<br />' . $names[$count] . '<br />');
         $count++;
    }
    
    点赞 评论 复制链接分享

相关推荐