php数组foreach循环

sha*_*ane 2 php foreach loops 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.
             }
        }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

奥兹

Ale*_*lec 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
        )

)
Run Code Online (Sandbox Code Playgroud)

首先,您需要遍历数组的所有单个元素$_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
  )
  */
}
Run Code Online (Sandbox Code Playgroud)

现在您想知道id产品的产品是否与您正在寻找的产品的ID相匹配.$product假设您的ID始终被命名为"id" ,则不需要遍历数组的每个元素来执行此操作.只需检查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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  Array
(
    [count] => 12
    [id] => 5
    [name] => some name
    [color] => some color
)
Run Code Online (Sandbox Code Playgroud)

如果你经历了所有的值,就像你现在做的那样,并尝试将其与某个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
  }
}
Run Code Online (Sandbox Code Playgroud)

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

祝好运!