如何将重复的数据删除到数组中

时间:2019-05-08 02:10:57

标签: php arrays multidimensional-array

需要帮助的代码。

这是我要删除两(2)个Wi-fi的阵列列表。

Array
(
    [20-10] => Array
        (
            [facilityCode] => 20
            [facilityGroupCode] => 10
            [order] => 1
            [number] => 1968
            [voucher] => 
            [description] => Year of construction
        )

    [550-70] => Array
        (
            [facilityCode] => 550
            [facilityGroupCode] => 70
            [order] => 1
            [indFee] => 
            [indYesOrNo] => 1
            [voucher] => 
            [description] => Wi-fi
        )

    [20-60] => Array
        (
            [facilityCode] => 20
            [facilityGroupCode] => 60
            [order] => 1
            [indLogic] => 1
            [voucher] => 
            [description] => Shower
        )


    [261-60] => Array
        (
            [facilityCode] => 261
            [facilityGroupCode] => 60
            [order] => 1
            [indFee] => 
            [indYesOrNo] => 1
            [voucher] => 
            [description] => Wi-fi
        )

)

我也尝试过array_unique();

结果如下:

Array
(
    [0] => Year of construction
    [1] => Shower
    [2] => Wi-fi

)

但是我想保留facilityCode,facilityGroupCode,order,number等。 感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

一个衬板就可以满足您的要求,

$result = array_reverse(array_values(array_column(array_reverse($arr), null, 'description')));

您需要的来源link

答案 1 :(得分:1)

//populate data
$mainArr = array();
$first = array(
    "facilityCode" => 20,
    "facilityGroupCode" => 10,
    "order" => 1,
    "number" => 1968,
    "voucher" => "",
    "description" => "Year of construction",
);
$second = array(
    "facilityCode" => 550,
    "facilityGroupCode" => 70,
    "order" => 1,
    "indFee" => "",
    "indYesOrNo" => 1,
    "voucher" => "",
    "description" => "Wi-fi"
);

$mainArr["20-10"] = $first;
$mainArr["550-70"] = $second;
$mainArr["261-60"] = $second;

//get duplicates
$counter = 0;
$duplicates = array();

foreach ($mainArr as $key=>$val) {
    $counter++;
    if (in_array($key, $duplicates)) continue;
    $i = 0;

    foreach ($mainArr as $key1=>$val1) {
        if ($i < $counter) {
            $i++;
            continue;
        }

        if ($val["description"] == $val1["description"]) {
            array_push($duplicates, $key1);
        }
    }
}

//remove duplicates
foreach($duplicates as $key) {
    unset($mainArr[$key]);
}

答案 2 :(得分:1)

$itemRows = array(); // Your main array
$descriptionValues = array();

foreach ($itemRows as $itemKey => $itemRow) {
    foreach ($itemRow as $key => $value) {
        if ($key == 'description') {
            if (in_array($value, $descriptionValues)) {
                unset($itemRows[$itemKey]);

                continue 2;
            }

            $descriptionValues[] = $value;
        }
    }
}