迭代PHP数组并检查重复值

时间:2016-11-17 19:56:49

标签: php arrays

我还是PHP的新手,我正在创建一个由一个人及其车辆组成的PHP数组。

示例:

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

问题:

迭代数组并为人A标记重复的BMW车辆的正确方法是什么?

感谢您的时间和帮助!

1 个答案:

答案 0 :(得分:1)

在读完你的问题后(​​虽然很模糊),我想我知道你在追求什么。

我编写了一些PHP代码,将所有数据加载到临时对象中。在将此附加到临时阵列之前,脚本会检查所有者是否已拥有汽车。然后,您可以选择如何处理重复条目。

注意:我已经修改了一下你的初始数组,以使这个脚本有效。

`

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

`

这是一个现场演示: http://phpfiddle.org/main/code/di0v-ugyr