如何使用函数添加具有键值的数组?

时间:2014-10-14 05:53:26

标签: php function multidimensional-array

我是非常新的PHP所以我很确定我的语法错了。我也理解简单地添加到数组可能更好,但我的问题更多是出于学习目的:

这是我的代码。我做错了什么?

<?php
    // list of players
    $currentPlayers = array(
        "player1" => array(
            "name"   => "Ryan",
            "age"    => 26,
            "weight" => 200,
        ),
    );
    // function to add a new person
    function addPlayer($nextPlayer, $name, $age, $weight) {
        $currentPlayers[$nextPlayer]["name"] = $name;
        $currentPlayers[$nextPlayer]["age"] = $age;
        $currentPlayers[$nextPlayer]["weight"] = $weight;
    }
    addPlayer("player2", "Joe", 23, 180);
    echo $currentPlayers["player2"]["name"];
?>

3 个答案:

答案 0 :(得分:4)

$currentPlayers未在addPlayer范围内定义,您需要通过更改函数的签名来导入它:

function addPlayer($nextPlayer, $name, $age, $weight) {
    globals $currentPlayers;

    // logic here
}

另一种选择(因为PHP喜欢有多种方式做某事):

function addPlayer($nextPlayer, $name, $age, $weight) {
    $currentPlayers = $GLOBALS['currentPlayers'];

    // logic here
}

答案 1 :(得分:0)

您也可以通过以下方式执行此操作:

function addPlayer(&amp; $ currentPlayers,$ nextPlayer,$ name,$ age,$ weight){ }

addPlayer($ currentPlayers,&#34; player2&#34;,&#34; Joe&#34;,23,180);

答案 2 :(得分:0)

请查看此处了解有关变量范围的更多信息。

如果你想用一个函数来做,这也可行:

$currentPlayers = array(
    "player1" => array(
        "name"   => "Ryan",
        "age"    => 26,
        "weight" => 200,
    ),
);
// function to add a new person
function addPlayer($name, $age, $weight) {
    return array("name" => $name, "age" => $age, "weight" => $weight);
}
$currentPlayers["player2"] = addPlayer("Joe", 23, 180);
echo $currentPlayers["player2"]["name"];