0

I am still new to PHP and I am creating a PHP array that consists of a person and their vehicle.

Example:

Array
(
    "owner" => "Person A",
    "car" => "BMW"
),
Array
(
    "owner" => "Person B",
    "car" => "Mercedes"
),
Array
(
    "owner" => "Person B",
    "car" => "BMW"
),
Array
(
    "owner" => "Person A",
    "car" => "BMW"
),
Array
(
    "owner" => "Person A",
    "car" => "DODGE"
)

Question:

What would be the proper way to iterate through the array and flag the duplicate BMW vehicle for Person A?

Thank you for your time and help!

1

1 Answer 1

1

After reading your question (although pretty vague), I think I know what you're after.

I have written a little bit of PHP code that loads all data into a temporary object. The script checks if an owner already owns a car, before appending this to the temporary array. You can then choose what to do with a duplicate entry.

Note: I have modified your initial array a little bit, to make this script work.

`

$data = (object) array
    (
    array (
        "owner" => "Person A",
        "car" => "BMW"
    ),
    array (
        "owner" => "Person B",
        "car" => "Mercedes"
    ),
    array (
        "owner" => "Person B",
        "car" => "BMW"
    ),
    array (
        "owner" => "Person A",
        "car" => "BMW"
    ),
    array (
        "owner" => "Person A",
        "car" => "DODGE"
    )

);

$temp = (object) array();
// loop over the object to list every person
foreach($data as $row){

    // check if person already exists in the temp array, if not add it
    if(!property_exists($temp, $row['owner'])){
      $temp->$row['owner'] = array();
    };

    // load the cars into the right persons array
    if(in_array($row['car'], $temp->$row['owner'])){
        // Duplicate car.. do something.
    } else {
      array_push($temp->$row['owner'], $row['car']);
    }

}

echo "<pre>";
print_r($temp);
echo "</pre>";

`

Here is a live demo: http://phpfiddle.org/main/code/di0v-ugyr

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.