【问题标题】:JSON data not showing on PHP when i select specific value当我选择特定值时,JSON 数据未显示在 PHP 上
【发布时间】:2021-04-02 19:48:49
【问题描述】:

我有一个 json 文件,我需要将其解析为 php 并仅显示一些我需要的值

<?php
// Read JSON file
$readjson = file_get_contents('output.json') ;

//Decode JSON
$data = json_decode($readjson, true);

//Print data
echo "<br/><br/> Employee names are: <br/>";

//Parse the employee name
foreach ($data as $emp) {
  echo $emp['category.name']."<br/>";
}
?>

output.json 文件包含一些值,例如:

    {
   "bizCode":10000,
   "message":"0#0",
   "data":[
      {
         "id":"sr:tournament:27070",
         "events":[
            {
               "homeTeamName":"Independiente Santa Fe",
               "awayTeamName":"America de Cali",
               "sport":{
                  "name":"Football",
                  "category":{
                     "name":"Colombia",
                     "tournament":{
                        "name":"Primera A, Apertura"
                     }
                  }
               },
            },
            {
               "homeTeamName":"AD Cali",
               "awayTeamName":"Millonarios FC",
               "sport":{
                  "name":"Football",
                  "category":{
                     "name":"Colombia",
                     "tournament":{
                        "name":"Primera A, Apertura"
                     }
                  }
               },
            }
         ],
         "categoryName":"Colombia",
      }
   ]
}

我已经测试过了,但它没有显示任何数据,我也找不到问题所在。也许问题是我找不到数据的确切路径?

【问题讨论】:

  • 这正是你的问题。你想要的数据在'events',而不是'data',所以你必须更深一层。此外,这不是有效的 PHP 语法:$emp['category.name'] - 您似乎将 JS 混入其中。对多个索引的正确 PHP 数组访问是将这些索引一个接一个地放置:$emp['category']['name']
  • 可能还值得一提的是,您在问题中说“员工姓名”,但您的 JSON 似乎包含足球比赛数据。也许您展示了错误的 JSON 示例?或者您的代码没有提取正确的文件?
  • @El_Vanja json 和代码是正确的,我只是在我之前工作的其他项目中放了一些文本。我已将代码更改为此处// Read JSON file $readjson = file_get_contents('output.json') ; //Decode JSON $events = json_decode($readjson, true); //Print data echo "&lt;br/&gt;&lt;br/&gt; Print: &lt;br/&gt;"; //Parse the employee name foreach ($events as $emp) { echo $emp['category']['name']."&lt;br/&gt;"; }
  • 请通过编辑对问题进行任何更改(edit 链接可以在您的帖子底部找到),而不是在 cmets 中。
  • 那是因为你忽略了我评论的前半部分。您没有在正确的级别进行迭代。阅读链接的问题,它有详细的说明。

标签: php json


【解决方案1】:

你的json格式不对,wrong format,你可以用任何类似这样的工具来验证 check here.also我为你格式化{"bizCode":10000,"message":"0#0","data":[{"id":"sr:tournament:27070","events":[{"homeTeamName":"Independiente Santa Fe","awayTeamName":"America de Cali","sport":{"name":"Football","category":{"name":"Colombia","tournament":{"name":"Primera A, Apertura"}}}},{"homeTeamName":"AD Cali","awayTeamName":"Millonarios FC","sport":{"name":"Football","category":{"name":"Colombia","tournament":{"name":"Primera A, Apertura"}}}}]}]}

您可以将其替换为您的 json 文件和 print_r($data)

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    相关资源
    最近更新 更多