1

首先让我解释一下我想要实现的目标:

我有一个用户项目数组,由 ID(item_id)和数量(例如 10 个项目)组成。如果用户购买了一个项目,它会被添加到包含数量的数组中。如果用户购买(在数组中)现有项目,则将“1”添加到数量中。

在这篇文章的帮助下,我非常接近:检查数组值是否存在于 PHP 多维数组中

这是我现在使用的代码:

 $item_id = arg(1);
  $quantity = '1';

  $found = false;
  $bought_items = null;
  $data = null;

  foreach ($user_items as $key => $data) {

    if ($data['a'] == $item_id) {
        // The item has been found => add the new points to the existing ones
        $data['b'] += 1;
        $found = true;
        break; // no need to loop anymore, as we have found the item => exit the loop
    } 
  }

  if ($found === false) {

      $bought_items = array('a' => $item_id, 'b' => $quantity);
  }

  $array = array($bought_items, $data);

如果 item_id 不存在,则将其添加到数组中 如果 item_id 存在,则数量将 'receive' +1

到目前为止,一切都很好

现在是实际问题,让我们勾画一下场景:

我购买项目 500 -> 数组包含:id=500,数量=1

我购买项目 500 -> 数组包含:id=500,数量=2

我购买项目 600 -> 数组包含:id=500,数量=2,id=600,数量=1

在这之后它出错了

然后我购买项目 500600,从阵列中删除另一个项目。因此,当我购买商品 500 时,商品 600 及其数量将从数组中删除。

我已经困惑了几个小时,但找不到错误,我知道我忽略了一些合乎逻辑的东西。我认为每个人都会出错。

4

2 回答 2

3

If bought_items is an array then you're overriding your values rather then adding them to the array.

$bought_items = array('a' => $item_id, 'b' => $quantity);

should be:

$bought_items[] = array('a' => $item_id, 'b' => $quantity);
于 2013-01-28T20:20:44.693 回答
1

我试过这个,它可以工作,所以你可以改变自己的使用。另一个帖子的代码对您的目的没有用

    $item_id = 500;
    $quantity = 1;

    $user_items = array(400, 300, 200, 500, 500, 200, 500, 500);
    $found = FALSE;
    $bought_items = null;
    $data = null;

    foreach ($user_items as $data) {

        if ($data == $item_id) {
            // The item has been found => add the new points to the existing ones
            $quantity += 1;
            $bought_items[$data]['a'] = $data;
            $bought_items[$data]['b'] = $quantity;
            $found = TRUE;
        }

        if ($found === FALSE) {

            $bought_items[$data] = array('a' => $data, 'b' => $quantity);
        }
        $found = FALSE;
    }
    print_r($bought_items);

输出:

array(4) {
   400 => array(2) {
      a => 400
      b => 1
   }
   300 => array(2) {
      a => 300
      b => 1
   }
   200 => array(2) {
      a => 200
      b => 3
   }
   500 => array(2) {
      a => 500
      b => 5
   }
}
于 2013-01-29T01:17:13.690 回答