我正在尝试遍历分配给对象的数组。函数entity_products_check()必须将提交的产品与数据库中预先保存的值数组进行比较。在所提供的测试示例中,foreach循环必须计算为true。但是,由于无法理解===运算符返回空(即null),XAMPP将其计算为false。由于一些奇怪的原因,只有在检查第一个值时才会发生这种情况。对于任何其他结果,它都会正确执行。我不明白为何会这样?
$entity=array("products"=>array("machine", "lollipop"));
class Borrowing_Cost
{
public array $entity;
public array $item;
public array $borrowing;
public function __construct($entity, $item, $borrowing)
{
$this->entity = $entity;
$this->item = $item;
$this->borrowing = $borrowing;
}
public function entity_products_check($arg){
$is_item = "";
**foreach ($this->entity["products"] as $value){
if($value === $arg){
$is_item = "true";
} else {
$is_item = "false";
}
}**
return $is_item;
}
}
$borr = new Borrowing_Cost($entity, $item, $borrowing);
echo $borr->entity_products_check("machine") . "<br>";发布于 2021-03-01 20:32:29
在您的代码中,您将每个项与您要寻找的值进行比较,因此在找到它之后,它仍然会转到下一个项上,并将标志设置为false。
此代码在开始时设置为false,只有在找到时将其标记为true,然后停止.公共函数entity_products_check($arg){ $is_item = "false";
foreach ($this->entity["products"] as $value){
if($value === $arg){
$is_item = "true";
break;
}
}
return $is_item;
}或者您可以使用in_array()检查值是否在数组中.
public function entity_products_check($arg){
return in_array($arg, $this->entity["products"])
? "true" : "false";
}https://stackoverflow.com/questions/66429056
复制相似问题