【问题标题】:How do I determine whether or not a particluar Key Combination is already in a MULTI-DIMENSIONAL associative array in PHP?如何确定特定的组合键是否已经在 PHP 的 MULTIDIMENSIONAL 关联数组中?
【发布时间】:2009-10-14 20:34:43
【问题描述】:

为了简化这个提出的问题,假设每个单元格都有一个行名和一个列名,可以正确地将您映射到相应的单元格。我正在遍历数据库记录并为二维数组中的某些字段创建一个位置,我将返回给调用者。我的问题是如何判断 array[rownName][colName] 中是否已经存在一个单元格?

这是我正在尝试做的事情的高级视图:

  //While there are more records:

  while ($row = mysql_fetch_assoc($result)) {

     //If this key doeesn't already exist in the return array, 
     //add this key/value pair.

     //Proper logic for determining whether or not a cell has already been 
     //created for this record would go here...

     $ret[$row['output_row_id']][$row['output_name']] = $row['output_value'];    
  }

提前感谢您的所有帮助!

【问题讨论】:

    标签: php multidimensional-array key


    【解决方案1】:

    如果您只想检查是否已设置特定键,可以使用 array_key_existsisset

    if(array_key_exists($row['output_row_id'],$ret) 
         && array_key_exists($row['output_name'],$ret[$row['output_row_id']])) {
    
        $ret[$row['output_row_id']][$row['output_name']] = $row['output_value'];
    }
    

    或:

    if(isset($ret[$row['output_row_id']][$row['output_name']])) {
    
        $ret[$row['output_row_id']][$row['output_name']] = $row['output_value'];
    }
    

    【讨论】:

    • 这非常有效。我正在寻找 array_key_exists 的文档,它似乎并不支持多维键。谢谢!
    猜你喜欢
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 2022-08-18
    • 1970-01-01
    • 2011-08-25
    • 2021-03-16
    • 2015-09-23
    相关资源
    最近更新 更多