将函数应用于数组中的每个元素(O'Reilly 食谱示例)

applying a Function to Each element in an array (O'Reilly cookbook example)

对于嵌套数据。

我试过了

<?php

$names = array('firstnames' => array("Baba", "Billy"),
'lastnames' => array("O'Riley", "O'Reilly"));

array_walk_recursive($names, function (&value, $key) {
    $value = htmlentities($value, ENT_QOUTES);
})

foreach ($names as $nametypes) {
    foreach ($nametypes as $name) {
        print "$name\n";

    }
}



?>

(O'reilly PHP 食谱第 3 版中的示例)第 148 页

但我不断收到消息

T_String,预计 T_Variable

您的代码中有拼写错误(ENT_QUOTES,$value):

array_walk_recursive($names, function(&$value, $key) {
    $value = htmlentities($value, ENT_QUOTES);
});


foreach ($names as $nametypes) {
    foreach ($nametypes as $name) {
        print "$name\n";

    }
}

使用 &$value 而不是 &value 使用 ENT_QUOTES 而不是 ENT_QOUTES

它正在工作。

谢谢大家

<?php

$names = array('firstnames' => array("Baba", "Billy"),
'lastnames' => array("O'Riley", "O'Reilly"));

array_walk_recursive($names, function (&$value, $key) {
    $value = htmlentities($value, ENT_QUOTES);
});

foreach ($names as $nametypes) {
    foreach ($nametypes as $name) {
        print "$name\n";

    }
}



?>