php - 通过引用 array_walk 中使用的回调函数来传递变量
问题描述
对于我在这里使用的示例,我意识到我可以使用 array_keys,但我正在尝试学习如何使用诸如 array_map 和 array_walk 之类的东西。在这种情况下,array_walk()。
我正在尝试这段代码
$inventory = [
'Apples' => ['Golden Delicious', 'Granny Smith','Fuji'],
'Oranges' => ['Valencia', 'Navel', 'Jaffa']
];
$fruits = [];
array_walk($inventory, 'fruitTypes', $fruits);
function fruitTypes($value, $key, &$fruits) {
$fruits[] = $key;
}
但我收到以下错误:
Warning: fruitTypes(): Argument #3 ($fruits) must be passed by reference, value given
第 8 行是:
array_walk($inventory, 'fruitTypes', $fruits);
但是,如果我将第 8 行更改为:
array_walk($inventory, 'fruitTypes', &$fruits);
我收到以下错误:
Parse error: syntax error, unexpected token "&", expecting ")"
知道在这种情况下如何通过引用传递 $fruits 数组吗?
解决方案
再看一下这个例子:
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $prefix)
{
$item1 = "$prefix: $item1";
}
function test_print($item2, $key)
{
echo "$key. $item2\n";
}
echo "Before ...:\n";
array_walk($fruits, 'test_print'); //<< callback function
array_walk($fruits, 'test_alter', 'fruit'); //<< callback function and argument
echo "... and after:\n";
array_walk($fruits, 'test_print');
?>
上面的示例将输出:
Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple
描述
array_walk(array|object &$array, 可调用 $callback, 混合 $arg = null): bool
推荐阅读
- html - 在不移动 iframe 内容的情况下更改 iframe 大小
- sql - 这个 SQL CREATE + INSERT 批处理有什么问题?
- python-3.x - 从 .xml 文件解析数据并将其保存到 Python 中的 .tsv 文件
- python - 将带有日期时间键的字典转储到生成 TypeError 的 json 文件
- regex - 在 python 中使用正则表达式仅提取特定字符
- node.js - 从 Node.js 事件处理程序到生成器
- flutter - 以编程方式获取 Flutter 应用程序中 Dart 类中定义的所有“静态常量”
- java - 如何打乱一组对象(在处理中)?
- twincat - 隔离 CPU 的 TwinCAT 实时启动失败
- azure-devops - 在 Azure Pipelines 中运行预发布版本的 DotNetCoreCLI