我有一个 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/