Jump to content

Need help with accessing an array within JSON that contains a dash


GalenAltaiir
Go to solution Solved by requinix,

Recommended Posts

Hi I have a json file that I called from an API into a string. But I noticed that that the name for the array was 2 words seperated with a "-", I understand that normally I'm able to access the array and print it using

$object->ArrayName[index] but what do I do if the array if the array name contains a dash? $object->Array-Name[index] 

I'm fairly new to PHP and a complete begginer with JSON so sorry if this is a bit confusing. I wrote some simple code to recreate the issue I have.

Code:

$json_string = '{"name":"Jeff","age":20,"active":true,"column-names":["title1","title2"]}';

$object = json_decode($json_string);
printf('All done! Welcome to Homepage %s',$object->"column-names"[1]);

Output:

Parse error: syntax error, unexpected '"column-names"' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in FILE_LOCATION on line 14

 

Edited by GalenAltaiir
Link to comment
Share on other sites

  • Solution

While possible to do in object form like that, it would be easier to have json_decode give you an array instead.

$json_string = '{"name":"Jeff","age":20,"active":true,"column-names":["title1","title2"]}';

$array = json_decode($json_string, true);
printf('All done! Welcome to Homepage %s', $array["column-names"][1]);

 

  • Thanks 1
Link to comment
Share on other sites

12 hours ago, requinix said:

While possible to do in object form like that, it would be easier to have json_decode give you an array instead.

$json_string = '{"name":"Jeff","age":20,"active":true,"column-names":["title1","title2"]}';

$array = json_decode($json_string, true);
printf('All done! Welcome to Homepage %s', $array["column-names"][1]);

 

Awesome thanks, what should I do this if the json string was formatted bit more like this -
 

$json_string = '{"column-names":["address1","address2","address3","postcode", ...],"rows":["address":"123, Imaginary Road", "someotherdata": dataset, ..., "postcode":"H3L L00"]}';

and I wanted to print the address, and then a post code? The method you provided doesn't seem to work in that scenario (unless I'm formatting it wrong)

printf('All done! Welcome to Homepage %s',$array["rows"][0]);

 

Link to comment
Share on other sites

19 minutes ago, requinix said:

Where are you getting [0] from? I see "rows" and "address" and "postcode" but no 0...

(and yes, you are formatting the JSON wrong. {} are for key/value pairs, [] are for straight lists)

I tried different ways of accessing the "address", I tried 

$array["rows"][0]
$array["rows"]["address"]

but those didn't work. I'm just not sure how to print out the specific elements from columns and rows. The API gives me the json file in that format when I print it as a string, although I see I made a mistake when recreating the string. It looks more like this - 

 

$json_string = 
'{

"column-names":["address1","address2","address3","postcode", ...],
"rows":
[{"address":"123, Imaginary Road", "someotherdata": dataset, ..., "postcode":"H3L L00"

}]}';

 

Link to comment
Share on other sites

This

"rows": {...}

and this

"rows": [{...}]

are two distinctly different things.

To figure out what you have to use to access something, work from the outside in.

1  {
2      "column-names": [
3          "address1",
4          "address2",
5          "address3",
6          "postcode",
7          ...
8      ],
9      "rows": [
10         {
11             "address": "123, Imaginary Road",
12             "someotherdata": dataset,
13             ...,
14             "postcode": "H3L L00"
15         }
16     ]
17 }

If you want the "address" on line 11 then you have to go through:
1. The outermost thing is an object (line 1)
2. The "rows" member is an array (line 9)
3. The first item in that array is an object (line 10)
4. The "address" member

Since you told json_decode() that you want objects to be converted into arrays, then that means you:
1. Start with the thing returned to you by json_decode(), which will be an array
2. Get the "rows" member
3. Get the first member, which would be the 0th
4. Get the "address" member

In the real world, if you have something called "rows" that is a JSON [ ] array then you probably shouldn't be using direct offsets on it (eg, 0) but rather a loop to get all the things inside it.

  • Great Answer 1
Link to comment
Share on other sites

8 minutes ago, requinix said:

This

"rows": {...}

and this

"rows": [{...}]

are two distinctly different things.

To figure out what you have to use to access something, work from the outside in.

1  {
2      "column-names": [
3          "address1",
4          "address2",
5          "address3",
6          "postcode",
7          ...
8      ],
9      "rows": [
10         {
11             "address": "123, Imaginary Road",
12             "someotherdata": dataset,
13             ...,
14             "postcode": "H3L L00"
15         }
16     ]
17 }

If you want the "address" on line 11 then you have to go through:
1. The outermost thing is an object (line 1)
2. The "rows" member is an array (line 9)
3. The first item in that array is an object (line 10)
4. The "address" member

Since you told json_decode() that you want objects to be converted into arrays, then that means you:
1. Start with the thing returned to you by json_decode(), which will be an array
2. Get the "rows" member
3. Get the first member, which would be the 0th
4. Get the "address" member

In the real world, if you have something called "rows" that is a JSON [ ] array then you probably shouldn't be using direct offsets on it (eg, 0) but rather a loop to get all the things inside it.

Thank you! The API array is massive, so I was having a really hard time understanding it. Putting it like I did here, and having you explain it helped a lot. The code works now, and I got the result I wanted :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.