Okay, so I'm fairly new to PHP but it's enough like JS so I've been picking it up fairly quickly.
One issue I ran into the other day was getting the values from a JSON file.
My JSON file is 30,000 lines, but here's essentially what it looks like:
{
"congress": {
"Brown Sherrod": [{
"birthday": "1952-11-09"
}, {
"gender": "M"
}, {
"type": "sen"
}, {
"state": "OH"
}, {
"party": "Democrat"
}],
...
And anyway, it continues like that for another 29,000 + lines. My code to get the contents of the JSON file is this:
$data = json_decode(file_get_contents('path/to/file/convertcsv.json'), true);
It returns an array like this:
Array (
[0] => Array (
[birthday] => 1952-11-09
)
[1] => Array (
[gender] => M
)
[2] => Array (
[type] => sen
)
[3] => Array (
[state] => OH
)
[4] => Array (
[party] => Democrat
)
)
My issue I ran into is that I can't get the value of, say, ['birthday'] without using implode()
.
This works: $state = implode($data['congress'][$nameInput][3]);
, but this does not: $state = $data['congress'][$nameInput][3];
Is there a reason why? I've read the docs on implode()
(join array elements with string) and from what I gather from SO and the PHP docs this is how you get the value, but why? It makes no sense to have to convert the array to a string in order to get the value. In JavaScript to get the value from an array (or even a key-value) you just use the ['key'] or the [index] of the array, and it'll give you the value.
I feel like either I'm goofing on something major (not unlikely) or PHP is just weird -- probably the former. So, to reiterate my question (because I can ramble) am I making this too complex or is PHP just weird (and if so, is there a reason)?