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

时间:2014-08-23 18:09:18

标签: php json youtube

我使用youtube gdata获取视频链接。我使用的PHP代码:

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

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

网址为http://gdata.youtube.com/feeds/api/videos?q=whatever&v=2&max-results=5&format=1&alt=jsonc。这给了我以下输出:

 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

现在我需要以下内容:

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---]

名称是索引数组,如:

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

如何执行此操作?我使用了array_push或merge函数,但它只添加了一个数组,而不是像Title或Content这样的变量。

1 个答案:

答案 0 :(得分:1)

foreach之外的$count = 0;之外设置一个计数器,然后在foreach$count++;内。然后,您可以使用$names[$count];内的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++;
}