2012-12-29 43 views
-1

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> 

是否有實現這個的方法嗎? 感謝

+1

你應該看看的相關問題右側欄,你的問題已經被問和回答。 –

+0

但這是給我一個錯誤「類stdClass的對象無法轉換爲字符串」。也許是因爲其他問題不要求多維數組? – aurel

+0

很可能不是問題,但是你的代碼在這裏有一個語法錯誤:[$ items-> id] ['id]應該是:[$ items-> id] ['id'] – art2

回答

0
$intersection = array_intersect($arr1, $arr2); 
if (in_array($value, $intersection)) { 
    // both arrays contain $value 
} 
+0

雖然「class stdClass的對象無法轉換爲字符串」 – aurel

+1

但我收到此錯誤是因爲此答案不是特定於您的問題的。 – hakre

0

您可以嘗試

$items = array(
    0 => 
    (object) (array(
    'id' => 1, 
    'title' => 'Verity soap caddy', 
    'price' => '6.00', 
)), 
    1 => 
    (object) (array(
    'id' => 2, 
    'title' => 'Kier 30cm towel rail', 
    'price' => '14.00', 
)), 
); 


$cartItems = array(
     0 => array(
       'rowid' => 'c4ca4238a0b923820dcc509a6f75849b', 
       'id' => 1, 
       'qty' => 1, 
       'price' => '6.00', 
       'name' => 'Verity soap caddy', 
       'subtotal' => 6, 
     ), 
); 

$itemsIncart = array_reduce(array_uintersect($items, $cartItems, function ($a, $b) { 
    $a = (array) $a; 
    $b = (array) $b; 
    return $a['id'] === $b['id'] ? 0 : 1; 
}), function ($a, $b) { 
    $a[$b->id] = true; 
    return $a; 
}); 

foreach ($items as $item) { 
    if (array_key_exists($item->id, $itemsIncart)) 
     printf('<h1 class="inCart">%s *</h1>', $item->title); 
    else 
     printf('<h1>%s</h1>', $item->title); 
} 

輸出

<h1 class="inCart">Verity soap caddy</h1> 
<h1>Kier 30cm towel rail</h1> 
相關問題