我有一個PHP類,如下(代碼的一部分):維護元素在PHP陣列和更新的PHP
class myclass{
private static $arrX = array();
private function is_val_exists($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && $this->is_val_exists($needle, $element))
return true;
}
return false;
}
//the $anInput is a string e.g. Michael,18
public function doProcess($anInput){
$det = explode(",", $anInput);
if($this->is_val_exists($det[0], $this->returnProcess())){
//update age of Michael
}
else{
array_push(self::$arrX, array(
'name' => $det[0],
'age' => $det[1]
));
}
}
public function returnProcess(){
return self::$arrX;
}
}
調用代碼index.php
$msg = 'Michael,18';
myclass::getHandle()->doProcess($msg);
在我的網頁上說: index.php
,它一遍又一遍地調用函數doProcess()
。當函數被調用時,字符串被傳遞並存儲在一個數組中。在下一次通話中,如果讓我們說相同的名字再次通過,我想更新他的年齡。我的問題是我不知道如何檢查數組$arrX
是否包含名稱。從我自己的發現來看,當代碼被調用時,數組似乎被重新啓動(回到零元素)。我的代碼永遠不會更新,並始終轉到array_push
部分。希望有人能對此提出一些想法。謝謝。
檢查的關鍵是在陣列中,檢查出array_key_exists功能 - http://php.net/manual/en/function.array-key-exists.php :) – flauntster
你可以分享'$ arrX'的一些數據樣本! –
向我們顯示調用代碼 – niyou