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

标签 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,但现在格式相同,是否有内置函数可以执行此操作?如果没有,我怎样才能得到输出?

最佳答案

你可以这样做:

$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);

关于php - 将一系列 json 对象转换为单个 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50104925/

相关文章:

php - 可更改的自定义 JSON Ajax 循环

php - 在 MVC 框架中构建模型?

java - 将 JSON 作为 HTTP POST 参数发送 (Android/Java)

json - Tastypie如何在注入(inject)Post数据后获取自定义Json响应

php - SQL查询从两个表中抓取数据

php - 可以在 WHERE 子句中评估列别名吗?

javascript - jQuery 动画无法正确滚动

c# - Newtonsoft.Json.JsonReaderException : Unterminated string. 预期的分隔符

javascript - 如何使用javascript以逗号分隔的字符串转换json值

php - 在php中进行json编码后显示数组的键