PHP:如何在数组的数组上执行htmlspecialchar()?
2022-08-30 20:18:46
如何在数组对象数组上运行 PHP 函数?htmlspecialchars()
我有以下代码:
$result_set = Array
(
[0] => Array
(
[home_id] => 1
[address] => 4225 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 76798
)
[1] => Array
(
[home_id] => 8
[address] => 4229 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 75093
)
);
// this doesn't work since $result_set is an array of arrays and htmlspecialchars is expecting a string
htmlspecialchars($result_set, ENT_QUOTES, 'UTF-8'));
更新:
请注意,尽管下面有很多答案,但它们都不适用于数组的数组。下面的答案仅适用于简单数组。
我尝试了以下方法,但它不起作用:
array_walk_recursive($result_set, "htmlspecialchars", array(ENT_QUOTES,'UTF-8'))
我收到以下错误:htmlspecialchars() expects parameter 2 to be long, string given
更新 2
当我尝试:
function cleanOutput(&$value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
print_r($result_set);
print('-------');
print_r(array_walk_recursive($result_set, "cleanOutput"));
我得到以下不需要的输出:
Array
(
[0] => Array
(
[home_id] => 1
[address] => 4225 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 76798
)
[1] => Array
(
[home_id] => 8
[address] => 4229 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 75093
)
)
-------1
更新 3
当我尝试:
function cleanOutput(&$value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
$result_set = Array
(
[0] => Array
(
[home_id] => 1
[address] => 4225 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 76798
)
[1] => Array
(
[home_id] => 8
[address] => 4229 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 75093
)
);
$cleanedOutput = array();
foreach ($result_set as $rs) {
$cleaned[] = array_map("cleanOutput", $rs);
}
print_r($cleanedOutput);
我得到以下不需要的结果:
{'homes' : []}