0
我想寫一個「智能」數組搜索功能,將記住最後找到的項目。分配參考靜態變量
function &GetShop(&$shops, $id) {
static $lastShop = null;
if ($lastShop == null) {
echo "lastShop is null <br/>";
} else {
echo "lastShop: [" . print_r($lastShop, true) . "]<br/>";
}
if ($lastShop != null && $lastShop['id'] == $id) {
return $lastShop;
}
for ($i = 0; $i < count($shops); $i++) {
if ($shops[$i]['id'] == $id) {
$lastShop = &$shops[$i];
return $shops[$i];
}
}
}
$shops = array(
array("id"=>"1", "name"=>"bakery"),
array("id"=>"2", "name"=>"flowers")
);
GetShop($shops, 1);
GetShop($shops, 1);
GetShop($shops, 2);
GetShop($shops, 2);
然而,似乎是與行的發行人:
$lastShop = &$shops[$i];
當我運行這個功能,因爲它是,我得到這樣的輸出:
lastShop is null
lastShop is null
lastShop is null
lastShop is null
當我刪除「&」,而不是價值傳遞,它工作正常:
lastShop is null
lastShop: [Array ([id] => 1 [name] => bakery) ]
lastShop: [Array ([id] => 1 [name] => bakery) ]
lastShop: [Array ([id] => 2 [name] => flowers) ]
但是我想通過引用傳遞,因爲找到的數組需要隨後修改。有人遇到過這個問題,並可以建議他如何解決它?
似乎這不是解決問題(已經嘗試過),因爲按照[PHP文檔(http://www.php.net/manual/en/language.variables。 scope.php#language.variables.scope.static)函數中的靜態變量只在第一次調用時被初始化。 – quentinadam
@goldmine查看更新 – feeela
謝謝。你會對我如何實現我想要做的事情有任何建議嗎(即將引用存儲到數組中的最後一個找到的項)? – quentinadam