我可以在PHP中执行类似的操作吗?
开始学习使用CodeIgniter,我想知道什么是最好的方法是重新做这个循环来比较两个变量请我可以在PHP中执行类似的操作吗?,php,arrays,codeigniter,foreach,Php,Arrays,Codeigniter,Foreach,开始学习使用CodeIgniter,我想知道什么是最好的方法是重新做这个循环来比较两个变量请 <?php $user = array('name' => 'name', 'hasCat'=> 1, 'hasDog' => 0); $pets = array('hasCat', 'hasDog'); foreach($pets as $pet) { echo ($pet==$user->hasCat) ? 'checked' :
<?php
$user = array('name' => 'name', 'hasCat'=> 1, 'hasDog' => 0);
$pets = array('hasCat', 'hasDog');
foreach($pets as $pet) {
echo ($pet==$user->hasCat) ? 'checked' : '';
the hasCat ^ is the one I want to replace to $pets??
}
?>
您不能通过执行$user->hasCat访问数组值,这意味着hasCat是对象$user的变量。试试这个:
<?php
$user = array('name' => 'name', 'hasCat'=> true, 'hasDog' => false);
$pets = array('hasCat', 'hasDog');
foreach($pets as $pet) {
if($user[$pet]) echo $pet;
}
?>
1)您使用[]
访问数组元素,意味着$user[“hasCat”]
而不是$user->hasCat
2)1
不在$pets
中,因此您的三元值总是错误的。您到底想做什么?这可能更容易些。@Rizier123谢谢!真不敢相信我忘了。。。也许我想得太多了。另外,您需要使用多个数组,因为您当前有一个数组,其中名称
、hasCat
和hasDog
作为键,没有内部关联/连接。您需要的是如下=$user=array(0=>array('name'=>$name,'hasCat'=>1,'hasDog'=>0))
@junkfoodjunkie谢谢。我试试看。