的主要问题是,你正试图与对象的工作像数组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>
)
)
See Live Demo
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);
}
}
这个效果很好!我遇到它并决定在我自己的项目中使用它。谢谢! – 2013-03-02 05:54:34
@TyBailey你也可以看看http://stackoverflow.com/a/15034807/1226894它使用不同的过滤器不只是'htmlentities' – Baba 2013-03-02 09:48:00
谢谢。这很好。巧合的是,我的两个原始功能(至少为了我的目的)也是如此。这个问题似乎与我的jquery ajax请求。不知何故,即使PHP脚本正在发送已解码的响应,它也会对实体进行编码。当然,我会接受你的答案,因为它对于原始问题是100%正确的。再次感谢。 – 2013-03-07 06:22:30