[英](WORDPRESS) Convert and Loop through JSON with PHP Arrays in posts and pages
PLEASE NOTE BEFORE READING: 阅读前请注意:
The JSON string:
JSON字符串:
{"name":"MaartenPAC","level":30}
Im trying to output the JSON string inside a wordpress post with the following code:
我试图用以下代码在wordpress帖子中输出JSON字符串:
// 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?).
该插件采用了上面的php代码,并生成了可以粘贴在帖子中的简码(我想是可以将其视为“ php include”吗?)。 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. 上面的代码没有输出的主要原因是语法错误,并且很可能没有为输出启用PHP错误。
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. 这不是在PHP中定义数组的有效语法。 This should look like:
看起来应该像这样:
$profile1Array = ["name" => "MaartenPAC", "level" => 30];
Second, your foreach statement is wrong. 其次,您的foreach语句是错误的。 Since you are doing
$key => $value
, the $key
would be 'name', and the $value
would be 'MaartenPAC'. 由于您正在执行
$key => $value
,因此$key
将为'name',而$value
将为'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 如果是这样,那么您将得到一个数组作为JSON字符串,看起来像
{"name":"MaartenPAC","level":30}
那么您需要使用PHP函数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 用户名是MaartenPAC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.