【问题标题】:Iterate PHP Array and validate data迭代 PHP 数组并验证数据
【发布时间】:2016-11-17 22:28:54
【问题描述】:

说明:

使用 PHP,我有一个表单可以让用户创建传出订单。

用户可以选择他们想在特定的盒子中发送什么库存物品#给特定的客户。

我想向此表单添加验证,因为用户不应该能够为同一个框选择 2 个不同的客户#。

例子:

Person A -> Item A -> Box 1
Person A -> Item B -> Box 1
Person B -> Item C -> Box 2
Person B -> Item D -> Box 1 //!! <- This should not be possible because                                    
Person C -> Item E -> Box 3        //Person A is already using Box #1.

提交表单后,我正在创建一个这样的数组:

$data = (object) array
    (
    array (
        "customer" => "Person A",
        "item" => "Item A",
        "box" => "Box 1"
    ),
    array (
        "customer" => "Person A",
        "item" => "Item B",
        "box" => "Box 1"
    ),
    array (
        "customer" => "Person B",
        "item" => "Item C",
        "box" => "Box 2"
    ),
    array (
        "customer" => "Person B",
        "item" => "Item D",
        "box" => "Box 1"
    ),
    array (
        "customer" => "Person C",
        "item" => "Item E",
        "box" => "Box 3"
    )

);

问题:

如何遍历这个数组以验证每个人都有自己的 Box #?

这是我正在尝试的,但我卡住了:

$temp_arr = (object) array();

foreach($data as $row){

    if(!property_exists($temp_arr, $row['customer'])){
      $temp_arr->$row['customer'] = array();
    };

    //Load the boxes into the correct customer array
    if(in_array($row['box'], $temp_arr->$row['customer'])){
        //Duplicate 
    } else {
      array_push($temp_arr->$row['customer'], $row['box']);
    }

}

【问题讨论】:

  • 所以如果一个人有一个物品但使用了一个被拿走的盒子#该物品应该用注明的盒子#?
  • 如果一个盒子已经被拿走了,验证结束并警告用户他们不能为同一个盒子使用两个客户#

标签: php arrays validation


【解决方案1】:
<?php
   $used_boxes = array();
   $valid_data = array();
   foreach($data as $row){
       if(!in_array($used_boxes)){
          //Box not used
          $valid_data[$row['customer']] = $row['box'];
          $used_boxes[] = $row['box'] 
       }else{
          //Box already used
       } 
   }
   var_dump($valid_data);

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多