-1

重複の可能性:
配列の値が別の配列phpに存在することをどのように確認しますか?

ショッピングサイトを作成しています。簡単にするために、2つの配列があります。1つはすべてのアイテムを保持し、もう1つはカートに追加されたすべてのアイテムを保持します。

$ Items

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をループしながら、同様のIDが$cartItems配列に存在するかどうかを確認します。また、ループ内で追加$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>

これを実装する方法はありますか?ありがとう

4

2 に答える 2

2
$intersection = array_intersect($arr1, $arr2);
if (in_array($value, $intersection)) {
    // both arrays contain $value
}
于 2012-12-29T22:01:35.513 に答える
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>
于 2012-12-29T22:31:03.063 に答える