我在一个存储在变量中的文件中有一个JSON对象,但我可以';我似乎没有用它做任何我想做的事情,因为它嵌套在数组中


I have a JSON object in a file that I stored in a variable, but I can't seem to do anything I want with it because it is nested inside of an array

我的json文件的内容格式如下:

[
  {
    "id": 1,
    "keyword_filter": null,
    "name": "My Name ",
    "type": "some product",
    "sku": "1234567",
    "nested_obj": {
      "url": "http://someurl.com",
      "resource": "/orders"
    }
  }
]

我可以把它读成这样的变量:

$json_string = file_get_contents($jsonFile);

最终,我需要用它创建一个以制表符分隔的文件,但我似乎无法对它进行迭代

foreach($json_string as $item) {
    echo $item;
}

这给了我一个错误,说我在foreach循环中提供了一个无效的参数。

我试着把它读成这样的数组:

$json_array = file($jsonFile);
foreach($json_array as $item) {
    echo $item;
}

这会回显一个有1个项的数组,即JSON对象。

有人能告诉我如何进入JSON对象,这样我就可以迭代它吗?将其编码回JSON只需两次转义引号,解码后返回NULL。

如有任何帮助,我们将不胜感激。。。任何关于转换为制表符分隔文件的提示都将不胜感激,但我只需要第一步就可以了。

谢谢。

试试这个:

json_decode:将json字符串转换为数组:http://php.net/manual/en/function.json-decode.php

$array  = json_decode($json_string, true);
echo "<pre>";
print_r($array);
/// write the forech basd on the array out put.    
foreach($array as $item) {
    echo $item['id'];
}

我试过这个:

<?php
$str = '[
  {
    "id": 1,
    "keyword_filter": null,
    "name": "My Name ",
    "type": "some product",
    "sku": "1234567",
    "nested_obj": {
      "url": "http://someurl.com",
      "resource": "/orders"
    }
  }
]';

$array  = json_decode($str, true);
echo "<pre>";
print_r($array);
/// write the forech basd on the array out put.    
foreach($array as $item) {
    echo $item['id'];
}
?>

我得到了输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [keyword_filter] => 
            [name] => My Name 
            [type] => some product
            [sku] => 1234567
            [nested_obj] => Array
                (
                    [url] => http://someurl.com
                    [resource] => /orders
                )
        )
)
1

这就是你想要的输出。在数组的末尾,您可以看到1,它是echo $item['id']; 的值

您需要用它创建一个制表符分隔的文件

$json_string = json_decode(file_get_contents($jsonFile), true);
foreach ($json_string as $k => $vals){
 // tab delimited header
 if ($k == 0) {
  echo join ("'t", array_keys($vals))."'n";
 }
 // tab delimited row
 echo join ("'t", $vals)."'n";
}