PLEASE NOTE BEFORE READING:
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.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.