【问题标题】:foreach loop multidimensional array but only loop through array elements with specific keyforeach 循环多维数组,但仅循环遍历具有特定键的数组元素
【发布时间】:2017-09-11 08:13:29
【问题描述】:

我正在创建以下数组,其中包含所有产品及其所有类别:

$result = $wpdb->get_results("SELECT product_nr, category FROM erp_product_categories",ARRAY_A);
$product_categories = array();
  foreach($result as $row){
    $product_categories[$row["product_nr"]][] = $row["category"];
  }

(product_nr 为整数,category 为字符串)

然后我想检查产品的一个类别是否与另一个变量匹配,如果是,则返回 true:

foreach($product_categories[$ean] as $product_categorie) {
    $manages_post = in_array( $product_categorie, $this->term_link_conditions );

    if($manages_post == true){
        break;
    }
}
return $manages_post;

但我得到了错误

为 foreach() 提供的参数无效

难道不能只循环遍历具有特定键的数组元素吗?

编辑: 数组是这样的

Array
(
    [10001] => Array       //product_nr
    (
        [0] => 1           //category
        [1] => 4           //category
    )

    [10002] => Array
    (
        [0] => 1
        [1] => 20
    )
    //...
)

【问题讨论】:

  • $product_categories$ean 的值是多少?
  • 表示数组为空或不存在。
  • $product_categorie实际上是一个类别数组?你的命名太混乱了。它也不包含安全网。例如,如果产品没有类别,它不会出现在数组中,即使我希望产品 id 存在,但内容是类别的空数组。最后但同样重要的是,您是否考虑过仅查询 $ean 的类别,而不是获取所有类别然后在 PHP 代码中过滤它们?
  • 什么是 foreach 中的 $ean($product_categories[$ean] as $product_categorie) {
  • @Shibon $ean 与 'product_nr' 相同

标签: php multidimensional-array foreach


【解决方案1】:

你应该使用is_array函数检查你传递给foreach的是一个数组

如果您不确定它是否是一个数组,您可以随时使用以下 PHP 示例代码进行检查:

if (is_array($product_categories[$ean])) {

  foreach ($product_categories[$ean] as $product_categorie) {
   //do something
  }
}

检查所有的 foreach 语句,并查看 as 之前的内容,以确保它实际上是一个数组。使用var_dump 转储它。

【讨论】:

    【解决方案2】:

    试试这个:

    if(is_array($product_categories) && sizeof($product_categories) > 0) {
        foreach($product_categories as $key => $product_categorie) {
            if($manages_post = in_array($key, $this->term_link_conditions)){
                return $manages_post;
            }
        }
    }
    

    【讨论】:

    • 我不想检查 in_array 中的键,我想检查具有特定键的值 (product_nr (=ean) ) 例如,如果键是 10002,那么我想要以下检查值: [10002] => Array ( [0] => 1 [1] => 2 [2] => 8 //检查类别 1、2 和 8 )
    【解决方案3】:

    我想出了一个办法

    $product_category = $product_categories[$ean];
    
                if (is_array($product_category)) {
                    $matches = array_intersect($product_category, $this->term_link_conditions);
                    if(sizeof($matches) > 0){
                        $manages_post = true;
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      相关资源
      最近更新 更多