Possible Duplicate:
How check any value of array exist in another array php?如何检查两个数组中是否存在与php相同的值
我正在创建购物网站。为了简化,我有2个阵列,一个拥有我所有的项目和其他拥有所有被添加在车中的物品:
$项目
Array
(
[0] => stdClass Object
(
[id] => 1
[title] => Verity soap caddy
[price] => 6.00
)
[1] => stdClass Object
(
[id] => 2
[title] => Kier 30cm towel rail
[price] => 14.00
)
//a lot more
)
$ cartItems
Array
(
[0] => Array
(
[rowid] => c4ca4238a0b923820dcc509a6f75849b
[id] => 1
[qty] => 1
[price] => 6.00
[name] => Verity soap caddy
[subtotal] => 6
)
)
我想循环浏览$ cartItems并添加一个类(标识),如果某个商品也在购物车中。这是我想做到这一点
foreach($items as $items){
if($cartItems[$items->id]['id']){
echo '<h1 class="inCart">'. $item->title . '</h1>' //...
}else{
echo '<h1>'. $item->title . '</h1>' //...
}
}
上面的代码不工作 - 即使$cartItems[0]['id']
将返回我需要什么。我的想法是,当循环遍历$ items时,检查$cartItems
数组中是否存在类似的id。我还尝试在循环中添加$cartItems[$i]['id']
并增加$i
,但这并不奏效。 当然的HTML输出,我希望得到的(简化)
<h1 class="IsOnCart"> Item Title</h1>
<h1> Item Title</h1>
<h1 class="IsOnCart"> Item Title</h1>
<h1> Item Title</h1>
是否有实现这个的方法吗? 感谢
你应该看看的相关问题右侧栏,你的问题已经被问和回答。 –
但这是给我一个错误“类stdClass的对象无法转换为字符串”。也许是因为其他问题不要求多维数组? – aurel
很可能不是问题,但是你的代码在这里有一个语法错误:[$ items-> id] ['id]应该是:[$ items-> id] ['id'] – art2