我创建了一个PHP函数,通过使用trim和htmlentities来清理所有数组值,除了那些键存在于 $ ignore 数组中的值。
function htmlentities_recursive( $input, $ignore ) {
if( is_array( $input ) || is_object( $input ) ) {
foreach ($input as $key => &$c) {
if( !in_array( $key, $ignore ) ) {
$c = htmlentities_recursive( $c, $ignore );
}
}
return $input;
}
return htmlentities( trim( $input ) );
}
除了数组的第一个值之外,该函数大部分工作正常。例如,它适用于$ movies数组的所有值,除了第一个值“Rear Window&” (不清理这个值),并忽略所有关键字'director'的值。
$movies = array(
array(
"title" => "Rear Window&",
"director" => "Alfred Hitc<hcock&",
"year" => 1954
),
array(
"title" => " Full >Metal Jacket",
"director" => "Sta<nley Kubrick&",
"year" => 1987
),
array(
"title" => "Mean Stree&ts",
"director" => "Ma>rtin S<corsese",
"year" => 1973
)
);
$testIgnore = ['foo','director','two'];
print_r(htmlentities_recursive($movies, $testIgnore));
结果是 -
Array
(
[0] => Array
(
[title] => Rear Window&
[director] => Alfred Hitc<hcock&
[year] => 1954
)
[1] => Array
(
[title] => Full >Metal Jacket
[director] => Sta<nley Kubrick&
[year] => 1987
)
[2] => Array
(
[title] => Mean Stree&ts
[director] => Ma>rtin S<corsese
[year] => 1973
)
)
我怎样才能消除第一个值呢?
答案 0 :(得分:1)
这是对in_array
电话的严格比较问题。
https://secure.php.net/manual/en/function.in-array.php
function htmlentities_recursive( $input, $ignore ) {
if( is_array( $input ) || is_object( $input ) ) {
foreach ($input as $key => &$c) {
if( !in_array( $key, $ignore, true ) ) {
$c = htmlentities_recursive( $c, $ignore );
}
}
return $input;
}
return htmlentities( trim( $input ) );
}
外部数组上的零索引导致跳过整个第一个内部数组。显然in_array(0, ['hello', 'world'])
返回true,但in_array(1, ['hello', 'world'])
返回false。有趣的是,in_array(0, [])
是错误的。