首页 > 解决方案 > 通过引用 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

解决方案


再看一下这个例子:

<?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

这是来源:https ://www.php.net/manual/en/function.array-walk.php


推荐阅读