php - 调用“in_array”似乎不起作用
问题描述
我在 cakephp 中调用这个 php 类型,即“in_array”。基本上我正在检查两个字段在数组中是否可用。问题在于,通过这种方法,它应该通过检查字段是否在数组中来仅输出一条语句。结果就像跳过数组检查并输出两个不正确的语句。
这是我在 View.ctp 中的调用,
foreach($types as $type)
{
if(in_array(array($carId, $type->type_id), $types))
{
echo $this->Html->link(
'Remove',
['controller' => 'cars', 'action' => 'removeType'],
['class' => 'btn btn-success']
);
}else
{
echo $this->Html->link(
'Add',
['controller' => 'cars', 'action' => 'addType'],
['class' => 'btn btn-success']
);
}
这就是我调用我的数据库的方式:
$typesTable = TableRegistry::getTableLocator()->get("Types");
$types = $typesTable->find('all')->toArray();
$this->set('types', $types);
如果数据库中的 $carId 等于 $typesId,则输出结果应该是一个按钮 Remove,如果不等于 Add,则应该显示按钮。
解决方案
正如函数的PHP 文档所述:in_array()
除非设置了严格,否则使用松散比较搜索大海捞针。
意思是做
return in_array(['foo', 'bar'], $arr);
相当于
foreach($arr as $element) {
if ($element == ['foo', 'bar']) {
return true;
}
}
return false;
回到你的代码,你可能想要做的是
foreach($types as $type){
if(in_array($carId, $types) && in_array($type->type_id, $types))
{
//both $carId and $type->type_id are in the $types array
}else
{
//either one or both of them are not in the array
}
}
推荐阅读
- sql - 在第三张桌子上连接两张桌子
- java - Android Emulator 没有显示其他可用的 WIFI 信号
- angular - 为什么我的屏幕路由逻辑不起作用?
- c++ - 如何在 SDL ttf 中提高字体质量并动态显示文本和数字
- angular - 如何使用 Spring Boot 和 Angular 应用程序隐藏授权标头
- javascript - Electron showOpenDialog 箭头功能(event.send)不起作用
- android - 消费购买导致空对象引用
- sql-server - 如果单元格不为空,则计算出现次数
- apache - debian 上的 golang/apache/cgi --- apache 重定向停止工作
- javascript - 无法在 Netlify Lambda 函数中返回 mysql db 查询结果