如何遍历子数组以查看值是否以字符串形式返回

时间:2012-10-10 00:51:43

标签: php arrays loops foreach

以下是输出数组的示例:

Array ( [CART] => Array ( [ITEMS] => Array ( [0] => Array ( [product_id] => 269194 [variation_id] => 0 [options] => Array ( ) [quantity] => 1 [product_name] => 15 Top Hits for Easy Piano [product_code] => HL102668 [product_price] => 14.9900 [original_price] => 14.9900 [default_currency] => 1 [customer_group] => [product_fields] => Array ( ) ) [1] => Array ( [product_id] => 266421 [variation_id] => 0 [options] => Array ( ) [quantity] => 1 [product_name] => Whistle [product_code] => HD245839 [product_price] => 3.9900 [original_price] => 3.9900 [default_currency] => 1 [customer_group] => [product_fields] => Array ( ) ) ) [LAST_UPDATED] => 1349829499 [NUM_ITEMS] => 2 ) [JustAddedProduct] => [CHECKOUT] => Array ( ) )

每个独特产品都有一个数组(在这个例子中有2个独特的产品。)有时只有一个,有时可能有20个或更多的独特产品。

对我来说重要的是[product_code]。您可以在第一个数组中看到[product_code] => HL102668。在第二个中有[product_code] => HD245839。

如何查看[product_code]值中是否存在“HD”?如果是的话,我需要返回false。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

访问子数组:

  $products  = $array['CART']['ITEMS'];

循环遍历子数组:

   foreach ($products as $product)

检查product_code中是否存在HD,使用简单的strstr,或使用preg_match使用正则表达式(如果您对此感到满意)。

   if (strstr($product['product_code'], "HD")) {
          // Do your actions
   }