我有问题解析嵌套json与PHP

时间:2016-01-06 10:08:16

标签: php json

Json Data

{
"response": 
{
    "status": 
    {
        "version": "4.2",
        "code":             ,
        "message": "Success"
    },
    "songs": 
    [
        {
            "artist_id": "ARYUDWF12F2B89BB33",
            "artist_name": "The Weeknd",
            "id": "SOMVZDS14DDE5909E7",
            "song_hotttnesss": 0.721485,
            "title": "Can't Feel My Face"
        },
        {
            "artist_id": "ARTZYQN13EEEF973E7",
            "artist_name": "Kygo",
            "id": "SOJJAOR14C0CA2A061",
            "song_hotttnesss": 0.698138,
            "title": "Stole the Show"
        }
    ]
}
}

我的PHP数据

<?php 

    $jsondata = file_get_contents("hotsongs.json");
    $json = json_decode($jsondata, true);
    $output = "<ul>";
    foreach($json['songs'] as $song){
        $output .= "<h4>".$song['name']."</h4>";
        $output .= "<h4>".$song['title']."</h4>";
    }
    $output .= "</ul>";
    echo $output;

?>

4 个答案:

答案 0 :(得分:1)

json格式错误

{
   "response": 
 {
 "status": 
  {
    "version": "4.2",
    "code": "",//check here on your code
    "message": "Success"
 },
  "songs": 
  [
    {
        "artist_id": "ARYUDWF12F2B89BB33",
        "artist_name": "The Weeknd",
        "id": "SOMVZDS14DDE5909E7",
        "song_hotttnesss": 0.721485,
        "title": "Can't Feel My Face"
    },
    {
        "artist_id": "ARTZYQN13EEEF973E7",
        "artist_name": "Kygo",
        "id": "SOJJAOR14C0CA2A061",
        "song_hotttnesss": 0.698138,
        "title": "Stole the Show"
      }
   ]
  }
  }

答案 1 :(得分:1)

更正:

1)您的code属性没有任何价值。

至少应为空白("")。

这被视为错误,您的JSON格式不正确。

2)正确

foreach($json['songs'] as $song){

要:

foreach($json['response']['songs'] as $song){

答案 2 :(得分:0)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tCell"];
    //I have set CollectionView tag to 100 and Label tag to 50
    UICollectionView *collect = (UICollectionView *) [cell viewWithTag:100]; //if the view is CollectionView
    UILabel *lbl = (UILabel *) [cell viewWithTag:50]; //if it is a UILabel
    return cell;
}

答案 3 :(得分:0)

循环时使用$json['response']['songs']

$jsondata = file_get_contents("hotsongs.json");
$json = json_decode($jsondata, true);
$output = "<ul>";
foreach($json['response']['songs'] as $song){

$output .= "<h4>".$song['name']."</h4>";
$output .= "<h4>".$song['title']."</h4>";

}
$output .= "</ul>";


print_r($output);