Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php remove duplicates based on first value of multidimensional array

Given

[0] => Array
    (
        [0] => ask.com
        [1] => 2320476
    )

[1] => Array
    (
        [0] => amazon.com
        [1] => 1834593
    )

[2] => Array
    (
        [0] => ask.com
        [1] => 1127456
    )

I need to remove duplicate values solely based on first value, regardless of what any other subsequent values may be. Notice [0][1] differs from [2][1] yet I consider this as a duplicate because there are two matching first values. The other data is irrelevant and shouldn't be considered in comparison.

like image 317
Jared Eitnier Avatar asked Aug 07 '26 10:08

Jared Eitnier


1 Answers

Try this, assuming that $mainArray is the array you have.

$outputArray = array(); // The results will be loaded into this array.
$keysArray = array(); // The list of keys will be added here.
foreach ($mainArray as $innerArray) { // Iterate through your array.
    if (!in_array($innerArray[0], $keysArray)) { // Check to see if this is a key that's already been used before.
        $keysArray[] = $innerArray[0]; // If the key hasn't been used before, add it into the list of keys.
        $outputArray[] = $innerArray; // Add the inner array into the output.
    }
}
print_r($outputArray);
like image 158
Stegrex Avatar answered Aug 10 '26 01:08

Stegrex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!