主要问题是您尝试使用像数组is_object($data) || is_array($data)
这样的对象不会真正起作用,除非您将其转换object
为array
其他问题是基于不正确的变量名并且没有返回正确的变量您可以尝试
$std = new stdClass();
$std->title = array("x" => "<a>XXX</a>","y" => "<b>YYY</b>");
$std->body = "<p> THis is the Body </p>";
$var = array(
"a" => "I'll \"walk\" the <b>dog</b> now",
"b" => array("<b>Hello World</b>",array(array("Yes am <strong> baba </strong>"))),
"c" => $std
);
$class = new MyClassName();
$encode = $class->encode($var); // encode
$decode = $class->decode($encode); // decode it back
print_r($encode);
print_r($decode);
编码数组
Array
(
[a] => I'll "walk" the <b>dog</b> now
[b] => Array
(
[0] => <b>Hello World</b>
[1] => Array
(
[0] => Array
(
[0] => Yes am <strong> baba </strong>
)
)
)
[c] => stdClass Object
(
[title] => Array
(
[x] => <a>XXX</a>
[y] => <b>YYY</b>
)
[body] => <p> THis is the Body </p>
)
)
解码数组
Array
(
[a] => I'll "walk" the <b>dog</b> now
[b] => Array
(
[0] => <b>Hello World</b>
[1] => Array
(
[0] => Array
(
[0] => Yes am <strong> baba </strong>
)
)
)
[c] => stdClass Object
(
[title] => Array
(
[x] => <a>XXX</a>
[y] => <b>YYY</b>
)
[body] => <p> THis is the Body </p>
)
)
观看现场演示
class MyClassName {
function encode($data) {
if (is_array($data)) {
return array_map(array($this,'encode'), $data);
}
if (is_object($data)) {
$tmp = clone $data; // avoid modifing original object
foreach ( $data as $k => $var )
$tmp->{$k} = $this->encode($var);
return $tmp;
}
return htmlentities($data);
}
function decode($data) {
if (is_array($data)) {
return array_map(array($this,'decode'), $data);
}
if (is_object($data)) {
$tmp = clone $data; // avoid modifing original object
foreach ( $data as $k => $var )
$tmp->{$k} = $this->decode($var);
return $tmp;
}
return html_entity_decode($data);
}
}