Reputation: 31
I have a json file which has series of json arrays
["FIRST_COLUMN", "SECOND_COLUMN", "THIRD_COLUMN" ...]
["John", "Snow", "Game of Thrones", ...]
["Ned", "Snow", "Game of Thrones", ....]
...
but I want one single json object:
[
{"FIRST_COLUMN" : "JOHN", "SECOND_COLUMN" : "SNOW"... } ,
{"FIRST_COLUMN" : "Ned", "SECOND_COLUMN" : "SNOW"... } ,
]
I want to do this in PHP and when I use json_encode
I get a json but now in the same format, is there a built in function to do this? if not, how can I get the output ?
Upvotes: 2
Views: 73
Reputation: 26844
You can do something like:
$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);
This will result to:
[
{
"FIRST_COLUMN":"John",
"SECOND_COLUMN":"Snow",
"THIRD_COLUMN":"Game of Thrones"
},
{
"FIRST_COLUMN":"Ned",
"SECOND_COLUMN":"Snow",
"THIRD_COLUMN":"Game of Thrones"
}
]
If your original value is string and not a valid json, you can:
$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);
Upvotes: 2
Reputation: 42093
You need array_combine
, that's what you need:
$keys = ['firstName', 'lastName', 'age'];
$values = ['John', 'Snow', 27];
$myEntry = array_combine($keys, $values);
// --> ['firstName' => 'John', 'lastName' => 'Snow', 'age' => 27]
just json_decode
, loop through the entries, append the keys, json_encode
Upvotes: 0