2012-12-29 39 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> 
相关问题