I have a fairly simple multidimensional array that I need to dedupe. I also need to remove any key that has a value, so in the below code I would need to keep the second target/value of city/Paris (Array 3) and also remove the 6th Array.
Array
(
[0] => Array
(
[target] => city
[value] => London
)
[1] => Array
(
[target] => colour
[value] => Red
)
[3] => Array
(
[target] => city
[value] => Paris
)
[4] => Array
(
[target] => type
[value] => House
)
[6] => Array
(
[target] => name
[value] =>
)
[7] => Array
(
[target] => email
[value] => mail@gmail.com
)
[9] => Array
(
[target] => custom2
[value] => path/to/something
)
)
I can do this by:
- Flattening the array
- Assigning the target/value as new key/values (this automatically overwrites the later value if there are dupes)
- Remove any keys that have a value of
- Rebuild the array
This feels wrong and I'm sure there is a better solution using array_walk_recursive() as this would probably preserve the original keys and make for a more elegant solution.
This is my current code:
function _clean_and_dedupe_targeting($array) {
// First flatten the array.
$flattenned = array();
foreach ($array as $item) {
foreach ($item as $value) {
$flattenned[] = $value;
}
}
// Take alternate items as key/value pairs.
// THIS WILL OVERWRITE ANY DUPLICATES LEAVING THE ONE SET IN CONTEXT IN PLACE.
$keyval = array();
array_unshift($flatenned, false);
while (false !== $key = next($flattenned)) {
$keyval[$key] = next($flattenned);
}
// Remove any items with <REMOVE>
$remove_string = '<REMOVE>';
$remove_keys = array_keys($keyval, $remove_string);
// Remove any keys that were found.
foreach ($remove_keys as $key) {
unset($keyval[$key]);
}
// Rebuild the array as a multidimensional array to send to the js.
$targeting = array();
$i = 0;
foreach ($keyval as $target => $value) {
$targeting[$i] = array('target' => $target, 'value' => $value);
$i++;
}
return $targeting;
}