我有一个相当简单的多维数组,我需要重复数据删除。我还需要删除任何具有值的键,因此在下面的代码中我需要保留city / Paris的第二个目标/值(数组3)并删除第6个数组。
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 ) )
我可以这样做:
这感觉不对,我确信使用array_walk_recursive()有更好的解决方案,因为这可能会保留原始密钥并使解决方案更加优雅。
这是我目前的代码:
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;
}
答案 0 :(得分:0)
您的算法正是您要做的:
// flatten and remove empty values
$params = array();
foreach ($values as $value) {
if (!empty($value['value'])) {
$params[$value['target']] = $value['value'];
}
}
// rebuild array
$values = array();
foreach ($params as $target => $value) {
$values[] = array(
'target' => $target,
'value' => $value,
);
}