的主要問題是,你正試圖與對象的工作像數組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