0

我尝试搜索但找不到。抱歉,如果解决方案已经存在,则错过了...

代码

$json = '[{"id":"2","value":"1"},{"id":"1","value":"1"},{"id":"3", "value":""},{"id":"4","value":""},{"id":"5","value":""},{"id":"6" ,"值":""},{"id":"7","value":""},{"id":"8","value":""},{"id":"9 ","value":""},{"id":"10","value":"1"}]';

$myArray = json_decode($json);
  foreach ($myArray as $key => $v) {
    if ($v->id == 10 && ($v->value == 0 || $v->value == 1)) {
        echo 'Value found at array key ' . $key;
    }
}  

输出

在数组键 9 处找到的值

但这仅在我用单引号中的值静态指定 $json 时才有效......但在我的 joomla 项目中,值是在类变量的帮助下获取的,所以当我使用$json=$item->extra_fields而不是给它一个静态字符串时,$json它不起作用。 ......

代码

 $json=$item->extra_fields;
  $myArray = json_decode($json);
  foreach ($myArray as $key => $v) {
    if ($v->id == 10 && ($v->value == 0 || $v->value == 1)) {
        echo 'Value found at array key ' . $key;
    }
}  

输出

警告:在第 484 行的 /components/com_k2/views/item/view.html.php 中为 foreach() 提供的参数无效


更新:

echo "JSON: $json<br/><br/>";
echo "DUMP: ".var_dump($myArray);

输出

JSON: [{"id":"2","value":"1"},{"id":"1","value":"1"},{"id":"3","value":""},
{"id":"4","value":""},{"id":"5","value":""},{"id":"6","value":"<br \/>"},
{"id":"7","value":"<br \/>"},{"id":"8","value":"<br \/>"},{"id":"9","value":"<br \/>"},
{"id":"10","value":"1"}]

NULL DUMP: 

--> 对 json_decode 使用 true 不会改变输出

Stripslashes 也没有工作。检查 $item->extra_fields 是字符串类型

4

2 回答 2

0

This has nothing to do with your code, nor with the JSON data you're trying to decode, but is a PHP configuration error (or done on purpose). I've come across this multiple times, but simply put the function has been disabled. Note that the function is not working rather than actually disabled, but the result is the same, an empty return value.

Best solution is to use an alternative code (method) to decode your JSON data, which can be found on the PHP website:

function json_decode($json)
{
    $comment = false;
    $out = '$x=';

    for ($i=0; $i<strlen($json); $i++)
    {
        if (!$comment)
        {
            if (($json[$i] == '{') || ($json[$i] == '[')) $out .= ' array(';
            else if (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')';
            else if ($json[$i] == ':') $out .= '=>';
            else $out .= $json[$i];
        }
        else $out .= $json[$i];
        if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
    }

    eval($out . ';');
    return $x;
}

This code is not pretty, but it does the trick. I've used this code every now and then to decode JSON data on servers that have similar problems you describe and I've yet to come across data you can't decode using this function.

于 2011-06-20T14:25:16.397 回答
0

@KilZone:感谢您的回复。我还没有尝试过您的代码,但是从数据库中获取的字符串在浏览器中正确显示,但是当我通过查看源代码进行检查时,该字符串具有&quot;而不是双引号。

所以我只是使用下面的代码来替换,它解决了我的问题。

json_decode(str_replace("&quot;","\"",$item->extra_fields))

谢谢大家的回复。

于 2011-06-21T04:49:23.740 回答