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