PHP 函数内部 array_push(mainArr, subAssociativeArr) 的问题

PHP problem with array_push(mainArr, subAssociativeArr) inside a function

array_push(mainArr, subAssociativeArr) 在函数内部时不起作用。我需要一些关于此代码的帮助:

$store=array();
$samsung=array('id'=>'10','name'=>'samsung');
$sony=array('id'=>'11','name'=>'sony');

function addOne($store, $element){
    array_push($store, $element);
}
addOne($store, $samsung);

var_dump($store); //output: empty array 

然而,如果没有功能,它也能正常工作;像下面这样:

$store=array();
$samsung=array('id'=>'10','name'=>'samsung');
$sony=array('id'=>'11','name'=>'sony');
array_push($store, $samsung);
var_dump($store); //output: array is added 

那么,问题是什么???

你忘了return

function addOne($store, $element){
    $store[]=$element;
    return $store;
}
$store = addOne($store, $samsung);

如果你愿意,你也可以通过引用传递(这更符合你的代码):

function addOne(&$store, $element){
    $store[]=$element;
}
addOne($store, $samsung);

注意 &。这不是复制输入,而是更像是指向原始变量的指针,因此您可以直接更新它。 Ether 方式在这里很好,这实际上是开发人员选择的问题。例如,将两者混合起来非常容易:

//Don't do this
function addOne(&$store, $element){ //returns null
    $store[]=$element;
}
$store = addOne($store, $samsung); //sets $store to null

您可能不想这样做,所以我可以看到两种方式的争论。除非你有超大阵列,否则它可能并不重要。很容易忘记随机函数是通过引用传递的。

因此,请使用对您来说更有意义的任何方法。

P.S。 - 我拒绝使用 array_push,它很丑,我不喜欢它:)。执行 $store[]=$element;array_push($store,$element) 相同,只是它避免了不必要的函数调用。

干杯。

当它在一个函数中时,你有一个不同的范围。虽然 addOne 函数的参数具有相同的名称,但它们实际上是传递的变量的副本,而不是对它们的引用。

因此,当您 array_push() 在一个函数中时,您只会影响该函数范围内的变量,而不影响外部范围。

您可以 return $存储,或通过引用传递变量。

如果你想让它在一个函数中工作,你需要一个变量的引用。 PHP 中的引用定义为 &,它们类似于 C 或 C++ 中的 "pointers"。

试试这个:

function addOne(&$store, $element){
    array_push($store, $element);
}

addOne($store, $samsung);

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

http://www.php.net/manual/en/language.oop5.references.php