使用 HTML 个实体转换数组和对象

Convert array and object with HTML entities

我正在尝试编写一段代码,它将递归地将数组或对象中的每个字符串转换为安全的引号,以便在输入框中显示。

这是我写的一个数组,里面的部分是我从别人那里看到的。它适用于对象但不适用于数组,它似乎到达第二个数组,并输出一个字符串 "null"

function fixQuotes($item)
{
    if (is_object($item)) {
        foreach (get_object_vars($item) as $property => $value) {
            //If item is an object, then run recursively
            if (is_array($value) || is_object($value)) {
                fixQuotes($value);
            } else {
                $item->$property = htmlentities($value, ENT_QUOTES);
            }
        }
        return $item;
    } elseif (is_array($item)) {
        foreach ($item as $property => $value) {
            //If item is an array, then run recursively
            if (is_array($value) || is_object($value)) {
                fixQuotes($value);
            } else {
                $item[$property] = htmlentities((string)$value, ENT_QUOTES);
            }
        }
    }
}

如果它是两个数组深,它不会保存数组,它现在可以工作,而且它缺少数组上的 return。感谢阅读。

如果将来有人需要执行此操作的脚本,这里是固定代码的副本。

function fixQuotes($item)
{
    if (is_object($item)) {
        foreach (get_object_vars($item) as $property => $value) {
            //If item is an object, then run recursively
            if (is_array($value) || is_object($value)) {
                $item->$property = fixQuotes($value);
            } else {
                $item->$property = htmlentities($value, ENT_QUOTES);
            }
        }
        return $item;
    } elseif (is_array($item)) {
        foreach ($item as $property => $value) {
            //If item is an array, then run recursively
            if (is_array($value) || is_object($value)) {
                $item[$property] = fixQuotes($value);
            } else {
                $item[$property] = htmlentities((string)$value, ENT_QUOTES);
            }
        }
        return $item;
    }
}