使用数组进行PHP表单验证

时间:2012-02-24 16:41:52

标签: php arrays kohana kohana-orm

我有以下数据正在处理:

[item][1][supplier_id] = 1
[item][1][territory_id] = 1
[item][1][cost] = 99.99

[item][2][supplier_id] = 2
[item][2][territory_id] = 1
[item][2][cost] = 99.99

[item][3][supplier_id] = 3
[item][3][territory_id] = 2
[item][3][cost] = 99.99

我想执行验证检查以满足以下条件:

如果supplier_ids不同,我想确保供应商来自不同的地区。使用上面的示例,表单将失败,因为item[1]item[2]有来自同一地区的供应商。如果未包含item[2],则表单将验证。

1 个答案:

答案 0 :(得分:0)

这应该做你想要的:

$items[0]["supplier_id"]  = 1;
$items[0]["territory_id"] = 1;
$items[0]["cost"]         = 99.99;
$items[0]["valid"]        = true;

$items[1]["supplier_id"]  = 2;
$items[1]["territory_id"] = 1;
$items[1]["cost"]         = 99.99;
$items[1]["valid"]        = true;

$items[2]["supplier_id"]  = 3;
$items[2]["territory_id"] = 2;
$items[2]["cost"]         = 99.99;
$items[2]["valid"]        = true;

// Loop through all $items (forwards)
for ($i = 0; $i < count($items); $i++) {
  // Loop through all $items before $i (backwards)
  for ($j = $i-1; $j >= 0; $j--) {
    if ($items[$i]["supplier_id"] != $items[$j]["supplier_id"]) {
      // Skip
      continue;
    } elseif ($items[$i]["territory_id"] == $items[$j]["territory_id"]) {
      // Invalidate
      $items[$j]["valid"] = false;
      // Stop looking for matches
      break;
    }
  }
}