1

Explanation:

Using PHP, I have a form that lets users create outgoing orders.

The user is able to select what inventory item they would like to send in a specific box # to a specific customer.

I would like to add validation to this form because the user should not be able to select 2 different customers for the same box #.

Example:

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.

When the form is submitted I am creating an array like this:

$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"
    )

);

Question:

How do I go about iterating through this array to validate that every person has their own Box #?

This is what I am trying but I am getting stuck:

$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']);
    }

}
2
  • so if a person has an item but using a taken box # that item should go to the user with the noted box #? Commented Nov 17, 2016 at 22:33
  • If a box is already taken, the validation ends and the user is warned that they cannot use 2 customers for the same box # Commented Nov 17, 2016 at 23:01

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.