Working with Zach and json

My pal Zach
was asking about working with json and php. So I am writing him a quick example. Here is a very simple json string with Zach’s name and alternate names as well:

{“firstName”: {“name1”: “Zach”, “name2”: “Zack”, “name3”: “Zak”, “name4”: “Zachariah”}, “secondName”: { “name1”: “Danger”, “name2”: “Tickles”, “name3”: “Temple”, “name4”: “Tiberius”}, “lastName”: {“name1”: “Martini”, “name2”: “Marteen”, “name3”: “Martin”, “name4”: “Martian”}}

This str ing is stored in a json.txt file and after a file_get_contents(‘json.txt’) and  json_decode()  or

$zachAttack = json_decode(file_get_contents(‘json.txt’), true);

we can get a var_dump() that shows:

array(3) { [“firstName”]=> array(4) { [“name1”]=> string(4) “Zach” [“name2”]=> string(4) “Zack” [“name3”]=> string(3) “Zak” [“name4”]=> string(9) “Zachariah” } [“secondName”]=> array(4) { [“name1”]=> string(6) “Danger” [“name2”]=> string(7) “Tickles” [“name3”]=> string(6) “Temple” [“name4”]=> string(8) “Tiberius” } [“lastName”]=> array(4) { [“name1”]=> string(7) “Martini” [“name2”]=> string(7) “Marteen” [“name3”]=> string(6) “Martin” [“name4”]=> string(7) “Martian” } }  

So to get Zach’s name correctly from this string, in php we would:

echo $zachAttack[“firstName”][“name1”] . ‘ ‘ . $zachAttack[“secondName”][“name3”] . ‘ ‘ . $zachAttack[“lastName”][“name3”];

This returns :

Zach Temple Martin

This is a very simple example. In more complicated arrays you may need to specify the place in the array. Like $zachAttack[“firstName”][0][“name1”]

for example. Hope that helps you Zach!

 

 





Comments are closed.