将一系列json对象转换为单个json对象

时间:2018-04-30 16:54:37

标签: php json

我有一个json文件,其中包含一系列json数组

["FIRST_COLUMN", "SECOND_COLUMN", "THIRD_COLUMN" ...]
["John", "Snow", "Game of Thrones", ...]
["Ned", "Snow", "Game of Thrones", ....]
...

但我想要一个单独的json对象:

[
  {"FIRST_COLUMN" : "JOHN", "SECOND_COLUMN" : "SNOW"... } ,
  {"FIRST_COLUMN" : "Ned", "SECOND_COLUMN" : "SNOW"... } ,
]

我想在PHP中执行此操作,当我使用json_encode时,我得到一个json,但现在采用相同的格式,是否有内置函数来执行此操作?如果没有,我怎样才能获得输出?

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

$str = '[["FIRST_COLUMN", "SECOND_COLUMN", "THIRD_COLUMN"],["John", "Snow", "Game of Thrones"],["Ned", "Snow", "Game of Thrones"]]';

//Convert string to array
$arr = json_decode($str, true);

//Remove the first array and store it in a variable
$header = array_shift($arr);

//Loop thru the remaining array
$results = array_map(function ($n) use($header) {
    return array_combine($header,$n); //Combine the arrays
}, $arr );

//Convert array to string
echo json_encode($results); 

这将导致:

[  
   {  
      "FIRST_COLUMN":"John",
      "SECOND_COLUMN":"Snow",
      "THIRD_COLUMN":"Game of Thrones"
   },
   {  
      "FIRST_COLUMN":"Ned",
      "SECOND_COLUMN":"Snow",
      "THIRD_COLUMN":"Game of Thrones"
   }
]

如果你的原始值是字符串而不是有效的json,你可以:

$str = '
["FIRST_COLUMN", "SECOND_COLUMN", "THIRD_COLUMN"]
["John", "Snow", "Game of Thrones"]
["Ned", "Snow", "Game of Thrones"]
';

//Convert string to array | Explode by new line and filter.
$arr = array_filter(explode(PHP_EOL, $str),function($e){
    return trim($e) !== '';
});

//Remove the first array and store it in a variable
$header = json_decode(array_shift($arr), true);

$results = array_map(function ($n) use($header) {
    return array_combine($header,json_decode($n, true)); //Combine the arrays
}, $arr );

echo json_encode($results);

答案 1 :(得分:0)

您需要array_combine,这就是您所需要的:

$keys = ['firstName', 'lastName', 'age'];
$values = ['John', 'Snow', 27];
$myEntry = array_combine($keys, $values);
// --> ['firstName' => 'John', 'lastName' => 'Snow', 'age' => 27]

只需json_decode,遍历条目,附加密钥json_encode