问题描述
我正在尝试遍历分配给对象的数组。函数 entity_products_check() 必须将提交的产品与数据库中预先保存的值数组进行比较。 foreach 循环 在提供的测试示例中必须评估为真。但是,出于某些原因,我无法理解 === 运算符返回 empty(即 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,$borrowing);
echo $borr->entity_products_check("machine") . "<br>";
解决方法
在您的代码中,您将每个项目与您要查找的值进行比较,因此在找到它之后,它仍然会转到下一个项目并将标志设置为 false
。
此代码在开始时设置为 false
并且仅在找到时才标记它 true
然后停止...
公共函数 entity_products_check($arg){
$is_item = "假";
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";
}