我正在尝试创建一个适用于简单数组和嵌套数组的函数。到目前为止,函数看起来像这样:
function fnPrepareDataForBrowser($values)
{
$values = array_map('htmlspecialchars', $values);
return $values;
}
它适用于简单数组 - 例如:
Array
(
[Item ID] => 25469
[Item Desc] => spiral nails, 1"
[Standard Item] => yes
[Entry UOM] => lb
)
但它失败并显示消息“警告:htmlspecialchars()期望参数1为字符串,数组给定......”用于嵌套数组 - 例如:
Array
(
[0] => Array
(
[Item ID] => 25469
[Item Description] => spiral nails, 1"
[Standard Item] => yes
[Entry UOM] => lb
)
[1] => Array
(
[Item ID] => 25470
[Item Description] => finishing screws, 2.5"
[Standard Item] => no
[Entry UOM] => lb
)
[2] => Array
(
[Item ID] => 25576
[Item Description] => paint brush, 3"
[Standard Item] => no
[Entry UOM] => each
)
)
应该对函数进行哪些修改,以便它适用于简单数组和嵌套数组?
答案 0 :(得分:2)
试试这个:
<?php
/**
* Applies callback function recursively to every element of the given array.
*
* If the array contains inner arrays or objects, the callback is also applied
* to these.
*
* Caution: If $arrayOfObject is an object, only public members are processed.
*
* @param callback $func
* @param array|object $array
*
* @return array
*/
public static function array_map_recursive($func, $arrayOrObject)
{
$array = is_array($arrayOrObject) ? $arrayOrObject : get_object_vars($arrayOrObject);
foreach ($array as $key => $val) {
$array[$key] = is_array($val) || is_object($val)
? self::array_map_recursive($func, $val)
: call_user_func($func, $val);
}
return $array;
}
?>
答案 1 :(得分:1)
您可以使用此array_map_recursive函数。我从手册中偷了它。
function array_map_recursive($callback, $array) {
foreach ($array as $key => $value) {
if (is_array($array[$key])) {
$array[$key] = array_map_recursive($callback, $array[$key]);
}
else {
$array[$key] = call_user_func($callback, $array[$key]);
}
}
return $array;
}
答案 2 :(得分:1)
function fnPrepareDataForBrowser(& $values)
{
return is_array($values) ?
array_map('fnPrepareDataForBrowser', $values) :
htmlspecialchars($values);
}
$array = fnPrepareDataForBrowser( $your_array );
答案 3 :(得分:0)
这是否符合您的需求?
<?php
function fnPrepareDataForBrowser(&$values)
{
$result = array();
foreach ( $values as $k => $v )
{
if ( is_array( $v ) ) {
array_push( $result, array_map('htmlspecialchars', $v) );
}
}
return $result;
}
$tst = array(
array (
'Item ID' => 25469,
'Item Description' => "spiral nails & 1",
'Standard Item' => 'yes&',
'Entry UOM' => 'lb>'
),
array (
'Item ID' => 25470,
'Item Description' => "finishing screws & 2.5",
'Standard Item' => 'no&',
'Entry UOM' => 'lb<'
),
array (
'Item ID' => 25576,
'Item Description' => "paint brush & 3",
'Standard Item' => 'no&',
'Entry UOM' => 'each&'
)
);
$result = fnPrepareDataForBrowser($tst);
print_r( $result );
产生这些结果
Array
(
[0] => Array
(
[Item ID] => 25469
[Item Description] => spiral nails & 1
[Standard Item] => yes&
[Entry UOM] => lb>
)
[1] => Array
(
[Item ID] => 25470
[Item Description] => finishing screws & 2.5
[Standard Item] => no&
[Entry UOM] => lb<
)
[2] => Array
(
[Item ID] => 25576
[Item Description] => paint brush & 3
[Standard Item] => no&
[Entry UOM] => each&
)
)