php数组foreach循环

时间:2011-01-16 13:57:00

标签: php loops foreach return

我的购物篮是array,其中的每件商品都是array

在某些方面,我正在遍历每个项目以寻找ID匹配。当我有匹配时,我需要知道主basket数组中的Items位置,以便我可以执行更新和删除。

听起来很简单,但我坚持下去。

到目前为止我有这个

//Lets say there are 5 items in this basket array (each item is also an array)
foreach ($_SESSION['basket'] as $basketArray){

        //this loops through the items attributes (size, colour etc)
        //when the ID is a match, i need to find out what position I am at in the main     array
        foreach($basketArray at $key = > $value){

             if ($value == $itemID){

                   //now I just need to know how to return 0, 1, 2, 3,  or 4 so that i can do 'unset' later.
             }
        }
}

感谢您的帮助。

奥兹

1 个答案:

答案 0 :(得分:6)

说这是你的$_SESSION['basket']

Array
(
    [0] => Array
        (
            [id] => 12
            [name] => some name
            [color] => some color
        )

    [1] => Array
        (
            [id] => 8
            [name] => some name
            [color] => some color
        )

    [2] => Array
        (
            [id] => 3
            [name] => some name
            [color] => some color
        )

    [3] => Array
        (
            [id] => 22
            [name] => some name
            [color] => some color
        )

)

首先,您需要循环遍历数组$_SESSION['basket']的所有单个元素:

foreach ($_SESSION['basket'] as $i => $product) {
  /*
  $i will equal 0, 1, 2, etc.
  and is the position of the product within the basket array.

  $product is an array of itself, which will equal e.g.:

  Array
  (
      [id] => 12
      [name] => some name
      [color] => some color
  )
  */
}

现在您想知道产品的id是否与您要查找的产品的ID相匹配。假设您的ID将始终命名为“id”,则无需通过$product数组的每个元素来执行此操作。只需检查id字段:

foreach ($_SESSION['basket'] as $i => $product) {
  if ($product['id'] == $someId) {
    // at this point you want to remove this whole product from the basket
    // you know that this is element no. $i, so unset it:

    unset($_SESSION['basket'][$i]);

    // and stop looping through the rest,
    // assuming there's only 1 product with this id:
    break;
  }
}

请注意,检查值也存在危险,而不是检查键。假设你有一个像这样构建的产品:

  Array
(
    [count] => 12
    [id] => 5
    [name] => some name
    [color] => some color
)

如果你经历了所有的价值观,比如现在正在做,并尝试将其与某个ID相匹配,那么当这个ID恰好是“12”时会发生什么?

// the id you're looking for:
$someId = 12;

foreach ($product as $key => $value) {
  // first $key = count
  // first $value = 12
  if ($value == $someId) {
    // ...
    // but in this case the 12-value isn't the id at all
  }
}

所以:始终引用数组中的特定元素,在本例中为“id”(或者您在应用中使用的名称)。不要检查随机值,因为你不能完全确定它匹配时,这实际上是你正在寻找的正确值。

祝你好运!