To remove duplicates from a multidimensional array in PHP, you can use the following approach:
- Convert the multidimensional array into a single-dimensional array using
array_map()
andarray_merge()
functions. - Use the
array_unique()
function to remove duplicates from the single-dimensional array. - Convert the single-dimensional array back into a multidimensional array using the original array’s structure.
Here’s an example code to remove duplicates from a 2-dimensional array:
<?php
$input = array(
array(1, 2, 3),
array(2, 3, 4),
array(3, 4, 5),
array(1, 2, 3)
);
// Convert the input array into a single-dimensional array
$flattened = array_map('serialize', $input);
$flattened = array_unique($flattened);
// Convert the single-dimensional array back into a multidimensional array
$result = array_map('unserialize', $flattened);
print_r($result);
?>
This will remove any duplicates from the input array, and give you the following output:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 2
[1] => 3
[2] => 4
)
[2] => Array
(
[0] => 3
[1] => 4
[2] => 5
)
)
I found myself deeply moved by this piece. It’s rare to come across writing that doesn’t just inform but transforms. You’ve taken complex ideas and made them feel not just understandable but important. Reading this, I felt both challenged and comforted — a true testament to the power of your words.
Thank you