homepage Welcome to WebmasterWorld Guest from 54.237.98.229
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
JSON object name/value pairs to php variables
JSON to PHP
beaudettee

5+ Year Member



 
Msg#: 4585845 posted 7:34 pm on Jun 19, 2013 (gmt 0)

Hi All:
I have a multi-level JSON in the following format that I need to extract name/value pairs and assign the values to variables on the fly so I can print them out formatted in html (php).

I have no probeles getting the valid JSON dumped out and this post: [webmasterworld.com...] does an excellent job iterating and printing data into a table but the troubles I am having are:
- eliminating certain values in the JSON from being displayed
- assigning names to variables so I can format the values for output

Here is a sample of the truncated JSON:

"Categories":[
{
"Name":"Americas",
"ID":"12345",
"Countries":[
{
"Name":"Argentina",
"Partners":[
{
"Country":"Argentina",
"ID":"4321",
"LogoUrl":"logo1.jpg",
"Title":"Company A",
"AddressBlock":"123 Main Street",
"Phone":"444-555-1212",
"TollFree":"",
"Email":"info@CompanyA.com",
"Url":"http://www.CompanyA.com/",
"IsVisible":true,
"IsDistributor":false
}
]
},
{
"Name":"Brazil",
"Partners":[
{
"Country":"Brazil",
"ID":"5432",
"LogoUrl":"logo2.jpg",
"Title":"Company B",
"AddressBlock":"54 Center Street",
"Phone":"234-567-3600",
"TollFree":"",
"Email":"info@CompanyB.com",
"Url":"http://www.CompanyB.com",
"IsVisible":true,
"IsDistributor":false
},

"Name":"Canada",
"Partners":[
{
"Country":"Canada",
"ID":"Company C",
"LogoUrl":"logo3.Company C",
"AddressBlock":"1 Mll Road Floor 27\r\nCanton, ON",
"Phone":"555-66-7777",
"TollFree":"",
"Email":"info@CompanyC.com",
"Url":"http://www.CompanyC.com",
"IsVisible":true,
"IsDistributor":false
},

]
}
]
}

]


and here is the code I am using for a dump of the entire JSON:

$json = file_get_contents('https://secure.json');
$light = '#fff';
$tint = '#c0c0c0';
$bg=null;
$jsonIterator = new
RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST); // multiple lines only for this forum
if (count($jsonIterator) > 0) {
echo "<table border=\"1\">\n";
foreach ($jsonIterator as $key => $val) {
$bg = ($bg==$light)?$tint:$light;
if(is_array($val)) {
echo "<tr><td style=\"background:$bg\" colspan=\"2\">$key</td> </tr>\n";
}
else {
echo "<tr><td style=\"background:$bg\">$key</td><td style=\"background:$bg\">$val</td></tr>\n";
}
}
echo "</table>\n\n";
}
else { echo "<p>The iterator is empty.</p>"; }
?>


Ideally I would like to assign each name/value pair to it's unique variable and echo each associated set of values into one table cell ending up with a nicely styled list of Partners (I can certainly handle the styling). Variables added to show associated values:

$Region:Americas
$CountryName:Argentina
$LogoUrl:logo1.jpg,
$Title:Company A,
$AddressBlock:123 Main Street
$Phone:444-555-1212
$TollFree:""
$Email:info@CompanyA.com
$Url:http://www.CompanyA.com
$IsVisible":true,
Getting php to cooperate by assigning values on the fly has been a major challenge for me so any help would be greatly appreciated!

Thanks.

 

jatar_k

WebmasterWorld Administrator jatar_k us a WebmasterWorld Top Contributor of All Time 10+ Year Member



 
Msg#: 4585845 posted 8:08 pm on Jun 19, 2013 (gmt 0)

maybe you should take a look at json_decode [php.net] it will parse the json into an array, then you can assign/output/style from there

beaudettee

5+ Year Member



 
Msg#: 4585845 posted 8:51 pm on Jun 19, 2013 (gmt 0)

Thanks for the quick reply jatar_k. I have tried this:

$string = file_get_contents('https:/secure.json');
$json = json_decode($string, true);
foreach($json as $key => $value) {
echo $key;
if (gettype($value) == "object") {
foreach ($value as $key => $value) {
//# cannot get anything to echo here
}
}
}


It seems to only output 'Categories' which is the top level key and then nothing else. I am stuck with getting to a level deeper in the array and assigning/retrieving vars/values.

Can I dynamically title the variable to the array name (i.e. $Title, $Country, etc)? I am stuck on the syntax and how to dig deeper into the array.

Any ideas?

Thanks again!

beaudettee

5+ Year Member



 
Msg#: 4585845 posted 1:21 pm on Jun 20, 2013 (gmt 0)

I am getting closer..
I think I am getting closer but still no output from this:

$string = file_get_contents('https://secure.json');
$json = json_decode($string, true);
foreach($json as $key => $val) {
$$key = $val; //or $$key = $val;
echo $Name; //echo “Company A”;
}
}

jatar_k

WebmasterWorld Administrator jatar_k us a WebmasterWorld Top Contributor of All Time 10+ Year Member



 
Msg#: 4585845 posted 2:50 pm on Jun 20, 2013 (gmt 0)

the best way to figure out how to iterate through an array is to look at it

you can output the array that json_decode creates for you by using print_r

$json = json_decode($string, true);
print_r($json);

then you may need a nested loop for what you are doing or could even just loop through and access array elements directly, I don't see the reason to assign them and then do something with them again later, you could do all your formatting and output right in that loop

beaudettee

5+ Year Member



 
Msg#: 4585845 posted 5:19 pm on Jun 20, 2013 (gmt 0)

Thanks jatar_k. So I added this:

foreach($json as $key => $val) {
echo $key . ":" . $val . "<br/>";
}
and get:

Categories:Array

back as a result.

I am stuck with how to set up the nested loop to get to all the levels/data I need to get to.

If I add the "for each" loop above within itself I get the same result: Categories

Minuteman

5+ Year Member



 
Msg#: 4585845 posted 5:26 pm on Jun 20, 2013 (gmt 0)

I think jatar_k has it. After you print_r, you will get a list of the arrays that are inside the first array. Then you can print_r each of them individually and see their contents too (including keys).

foreach($json as $key => $val) {
echo $key . ":" . $val . "<br/>";
}
and get:

Categories:Array


try adding
print_r('Categories');

beaudettee

5+ Year Member



 
Msg#: 4585845 posted 5:27 pm on Jun 20, 2013 (gmt 0)

Also just tried this:

foreach($json as $fieldIndex => $fields) {
foreach($fields as $valueIndex => $envelope) {
foreach($envelope as $valueEntry) {
foreach($valueEntry as $key => $value) {
printf("%d - %d - %s: '%s'\n", $fieldIndex, $valueIndex, $key, $value);
$build[$valueIndex][$key]=$value;
}
}
}
}

which yields a dump of sorts in the format of :

0 - 0 - 0: 'Array' 0 - 0 - 1: 'Array' 0 - 0 - 2: 'Array' 0 - 0 - 3: 'Array' 0 - 0 - 4: 'Array' 0 - 0 - 5: 'Array' array(1) { [0]=> array(6) { [0]=> array(2) { ["Name"]=> string(9) "Argentina" ["Partners"]=> array(1) { [0]=> array(11) { ["Country"]=> string(9) "Argentina" ["ID"]=> string(36) "b1c79774-5969-4ae1-bfae-eea4d8c14d93" ["LogoUrl"]=> string(52) "http://www.aaa.com/images/partners/aaa.jpg" ["Title"]=> string(14) "Company S.A." ["AddressBlock"]=> string(118) "Main Street - Dock 8 12435- Anytown USA" ["Phone"]=> string(17) "(444) 123-4567" ["TollFree"]=> string(0) "" ["Email"]=> string(28) "info@aaa.com" ["Url"]=> string(35) "http://www.aaaa.com/" ["IsVisible"]=> bool(true) ["IsDistributor"]=> bool(false) } } }

How can I reference the individual name/value pairs at the right level?
etc...

beaudettee

5+ Year Member



 
Msg#: 4585845 posted 8:18 pm on Jun 20, 2013 (gmt 0)

Hi Minuteman:
This:

$string = file_get_contents('https://secure.json');
$json = json_decode($string, true);
print_r($json);


yields this (truncated):

Array ( [Categories] => Array ( [0] => Array ( [Name] => Americas [ID] => cd144e [Countries] => Array ( [0] => Array ( [Name] => Argentina [Partners] => Array ( [0] => Array ( [Country] => Argentina [ID] => c14d93 [LogoUrl] => aaaa.jpg [Title] => AAAA Cocrp [AddressBlock] => A Street, Anytown USA [Phone] => (555) 123-1212 [TollFree] => [Email] => info@aaaa.com [Url] => http://www.aaaa.com/ [IsVisible] => 1 [IsDistributor] => ) ) )

Adding:
foreach($json as $key => $val) {
print_r('Categories');
}


Simply prints out 'Categories' so I am sure I am missing something.

Thanks for the reply.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved