In PHP, we often need to process arrays, especially when the array contains multiple multi-dimensional arrays, the need to extract the value of a certain column and deduplicate it often occurs. Today, let's discuss how to combine array_column and array_unique functions to deduplicate the value of a column in an array.
First, we can extract the value of a column from a multidimensional array through the array_column function. The function of array_column is to return the value of a specified column in a multi-dimensional array, which is often used to extract a certain information in the data list.
For example, suppose we have an array of multiple records, each with fields such as id , name , and email , from which we want to extract all email addresses.
<?php
$data = [
['id' => 1, 'name' => 'Alice', 'email' => 'alice@m66.net'],
['id' => 2, 'name' => 'Bob', 'email' => 'bob@m66.net'],
['id' => 3, 'name' => 'Charlie', 'email' => 'alice@m66.net'],
];
$emails = array_column($data, 'email'); // Extract all email address
print_r($emails);
?>
After running the above code, the output result is:
Array
(
[0] => alice@m66.net
[1] => bob@m66.net
[2] => alice@m66.net
)
Next, we use the array_unique function to deduplicate the extracted email address. The array_unique function deletes duplicate values in the array and retains only unique values.
<?php
$uniqueEmails = array_unique($emails); // Go to the heavy
print_r($uniqueEmails);
?>
After running the above code, the output result is:
Array
(
[0] => alice@m66.net
[1] => bob@m66.net
)
As you can see, array_unique successfully removed the duplicate alice@m66.net address and only retained the unique email address.
By combining these two functions, we can implement the operation of extracting a certain column from a multi-dimensional array and deduplication. Here is a complete example showing how to extract email columns and deduplicate them.
<?php
$data = [
['id' => 1, 'name' => 'Alice', 'email' => 'alice@m66.net'],
['id' => 2, 'name' => 'Bob', 'email' => 'bob@m66.net'],
['id' => 3, 'name' => 'Charlie', 'email' => 'alice@m66.net'],
];
$emails = array_column($data, 'email'); // Extract all email address
$uniqueEmails = array_unique($emails); // Go to the heavy
print_r($uniqueEmails);
?>
The final output is: