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' : []}

答案 1

可以使用 array_map() 对每个条目运行该方法。

$cleaned = array_map("htmlspecialchars", $myArray);

如果需要将参数传递给 ,则可以将其替换为自己的自定义函数:htmlspecialchars()

function myFunc($a) {
  return htmlspecialchars($a, ENT_QUOES);
}

$cleaned = array_map("myFunc", $myArray);

考虑到您正在处理的是数组数组,而不是字符串数组,您需要循环遍历外部数组才能获得字符串:

$cleaned = array();
foreach ($result_set as $rs) {
  foreach ($rs as $r) {
    $cleaned[] = array_map("htmlspecialchars", $r);
  }
}

或者,您可以使用:array_walk_recursive()

array_walk_recursive($myArray, "htmlspecialchars");

请注意,此方法通过引用更改$myArray对象,因此无需将输出分配给新变量。


答案 2
function filter(&$value) {
  $value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
array_walk_recursive($result_set, "filter");
print_r($result_set);