0

PLEASE NOTE BEFORE READING:

  • Im making use of wordpress, divi and sportspress
  • Im trying to loop through these JSON strings and output them on my profile page (wordpress post)
  • Php code are added to posts with this plugin: Plugin Page
  • Im pulling JSON strings via an API(no problems encountered - only mentioning this here)
  • Im aware that there are similar questions, however, this is wordpress related and the answer could be either a solution for a WORDPRESS post OR a different implementation suggestion that might be more fitting for this CMS. This means im willing to change the methods used to output these strings :)

The JSON string:

{"name":"MaartenPAC","level":30}

Im trying to output the JSON string inside a wordpress post with the following code:

// Loop through Array
$profile1Array = {"name":"MaartenPAC","level":30}; // This is the PHP Array
foreach ($profile1Array as $key => $value) {
echo $value["name"] . ", " . $value["level"] . "<br>";
}

The Problem:

Im getting no output at all.I'm not sure if this is a syntax error perhaps? The plugin takes the php code above and generates a shortcode that can be pasted inside a post (one can think of it as a "php include" I guess?). Im still looking into this myself and will keep this question updated.

MaartenPAC
  • 43
  • 9

2 Answers2

1

The main reason you are getting no output with the above code is syntax error, and most likely, you do not have PHP Errors enabled for output.

Either, check your servers log file, or enable error output.

One of the main issues is your definition of a array:

$profile1Array = {"name":"MaartenPAC","level":30};

This is not a valid syntax to define an array in PHP. This should look like:

$profile1Array = ["name" => "MaartenPAC", "level" => 30];

Second, your foreach statement is wrong. Since you are doing $key => $value, the $key would be 'name', and the $value would be 'MaartenPAC'.

This should look like:

foreach( $profile1Array AS $key => $value ) {
    echo $key . ' is: ' . $level;
}

EDIT:

If it is so that you are getting an array as JSON string looking like {"name":"MaartenPAC","level":30} then you need to make use of the PHP function json_decode

Ole Haugset
  • 3,552
  • 3
  • 19
  • 41
0

The following loop works like a charm along with the plugin mentioned.

$array = json_decode('[{"name":"MaartenPAC","level":30}]');

foreach ($array as $key => $jsons) {
 foreach($jsons as $key => $value) {
if($key == 'name'){
echo "Username is " . $value;
}
}
}

Output:

Username is MaartenPAC

MaartenPAC
  • 43
  • 9