简体   繁体   English

在foreach中的PHP in_array()

[英]php in_array() inside a foreach

I am having issues with using in_array() inside a foreach loop. 我在foreach循环中使用in_array()有问题。 Not sure if this is even possible or if I am doing something ridiculous where there are better ways. 不知道这是否有可能,或者我是否在有更好的方法的地方做一些荒谬的事情。 What I want to do is go through all the items and if their item id matches one thats in the array, return true and add the price of the item to a runninng total. 我想要做的是遍历所有项目,如果它们的项目ID与数组中的多数民众赞成在匹配,则返回true并将该项目的价格加到总计中。

$price = 0;
$result = false;
$array = array(1533, 2343, 2333);

foreach($order['items'] as $item){
  if(in_array($item['Item'], $array)){
     $result = true;
     $price += $item['Price'];
  }
}

**UPDATED**
Here is the order array

[items] => Array
    (
        [0] => Array
            (
                [Item] => 139957
                [OrderID] => 16025
                [SizeID] => 24
                [Price] => 46.00
            )

        [1] => Array
            (
                [Item] => 2343
                [OrderID] => 16025
                [SizeID] => 12
                [Price] => 32.00
            )
    )

[data] => Array
    (
    )
$price = 0;
$result = false;
$array = array(1533, 2343, 2333);

foreach($order['items'] as $item){
  if(in_array($item['Item'], $array)){
     $result = true;
     $price += $item['Price'];
  }
}

if ($result)
{
    echo 'was true';
}
else
{
    echo 'was false';
}

Technically you don't even need the $result variable since if $price is more than 0 then of course it was true, unless the price of item was free ($0). 从技术上讲,您甚至不需要$ result变量,因为如果$ price大于0,那么当然是对的,除非项目的价格是免费的($ 0)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM