我有一个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
部分。希望有人能对此发表一些看法。非常感谢。
在doProcess()
函数的其他条件中缺少)
,它应该是:
else{
array_push(self::$arrX, array(
'name' => $det[0],
'age' => $det[1]
)); // <-- there was the missing )
}
以下是基于您的代码的完整运行解决方案:
<?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
for ($i=0; $i<count(self::$arrX); $i++) {
if (is_array(self::$arrX[$i]) && self::$arrX[$i]['name'] == $det[0]) {
self::$arrX[$i]['age'] = $det[1];
break;
}
}
} else{
array_push(self::$arrX, array(
'name' => $det[0],
'age' => $det[1]
));
}
}
public function returnProcess(){
return self::$arrX;
}
}
$mc = new myclass();
$mc->doProcess('Michael,18');
$mc->doProcess('John,23');
$mc->doProcess('Michael,19');
$mc->doProcess('John,25');
print_r($mc->returnProcess());
?>
您可以在这里进行测试:PHP可运行
正如我在评论中所说,看起来您希望在请求之间保持状态。您不能使用纯PHP来做到这一点,您应该使用外部存储解决方案。如果有,试试Redis,它有你需要的,而且使用起来很简单。或者,如果您熟悉SQL,您可以使用MySQL作为示例。
附带说明一下,您应该阅读更多关于PHP数组如何工作的信息。
- 您可以使用
self::$arrX[] = ...
而不是array_push - 相反,您可以使用关联数组,例如
self::$arrX[$det[0]] = $det[1];
,这将使查找更加容易(array_key_exists
等)
您可以尝试如下更新is_val_exists吗:
private function is_val_exists($needle, $haystack) {
foreach($haystack as $element) {
if ($element['name'] == $needle) {
return true;
}
return false;
}