如何编辑我的代码,以便它将打印JSON字符串的所有块,而不仅仅是第一个



我正在尝试从同一页面获取某些源文件的内容,并将其保存到MySQL中。有些文件的属性名称数量不同于其他文件,因此更多的"自动"代码将有所帮助。我粘贴在示例源文件下面,但是您可以在下面看到它的代码。

示例源文件:

{
Trims: [
{
   "model_id":"15155"
  ,"model_make_id":"ford"
  ,"model_name":"Taurus"
  ,"model_trim":""
  ,"model_year":"2000"
  ,...(all available model fields are included)
 },
{
   "model_id":"15073"
  ,"model_make_id":"ford"
  ,"model_name":"Taurus"
  ,"model_trim":"3.0"
  ,"model_year":"2000"
  ,...(all available model fields are included)
  },
  {etc...}
}]}

预期输出:

我只想仅打印一次属性名称,因为所有源文件的数字都相同。

model_id
model_make_id
model_name
model_trim
model_year
...and so on....
------
and afterwards all the values
15155
ford
Taurus
2000
...and so on...
15073
ford
Taurus
3.0
2000
...and so on...

第一次解决方法: http://codepad.viper-7.com/dzdxoo

我可以打印属性名称和值。但是有问题。我只需要一次属性名称,这还可以。但它仅打印一个值的第一个块,而不是其他值。如果我可以打印所有内容,这是我的解决方案。我正在工作的不同源文件中的属性名称数量不同,因此这有助于我自动获取名称。

<?php
$json = file_get_contents('http://www.carqueryapi.com/api/0.3/?cmd=getTrims&year=2007&make=mini');
$vres = array('{"Trims":' , '}]}');
$allakse = array("" , "}]");
$json = str_replace($vres, $allakse, $json);
$cars = json_decode($json, true);
foreach ($cars[0] as $key => $car)
{
  echo "$key", "n";
}
echo"<br><br>";
foreach ($cars[0] as $key => $car)
{
  echo "$car", "n";
}

第二个解决方法: http://codepad.viper-7.com/7bcdux

由于源文件具有不同数量的属性,因此拥有固定的for each - echo loop不会帮助我。这是必不可少的,因为我想从每个源文件自动获取属性名称。另外,我不能打印属性名称,只有值。

<?php
$json = file_get_contents('http://www.carqueryapi.com/api/0.3/?cmd=getTrims&year=2007&make=mini');
$cars = json_decode($json, true);
foreach($cars['Trims'] as $car){
    echo $car['model_body'].'<br/>';
}

我应该如何回应所有块中的所有值,而不是从第一个块?

回声

当您具有解码的JSON时,您可以在任何项目的数组和打印标头上操作(让我们选择第一个项目),然后从数组中的所有项目中打印值:

<?php
function PrintFieldNames($item)
{
    foreach($item as $key => $value) 
    {
        echo($key . "<br/>");
    }
}
function PrintFieldValues($item)
{
    foreach($item as $key => $value) 
    {
        echo($value . "<br/>");
    }
}
$json = file_get_contents('http://www.carqueryapi.com/api/0.3/?cmd=getTrims&year=2007&make=mini');
$cars = json_decode($json, true);
$cars = $cars['Trims'];
PrintFieldNames($cars[0]);
foreach($cars as $car)
{
    PrintFieldValues($car);
}
?>

最新更新