-1

我有一个相当简单的多维数组,我需要对其进行重复数据删除。我还需要删除任何具有值的键,因此在下面的代码中,我需要保留 city/Paris 的第二个目标/值(数组 3)并删除第 6 个数组。

大批
(
    [0] => 数组
        (
            [目标] => 城市
            [价值] => 伦敦
        )

    [1] => 数组
        (
            [目标] => 颜色
            [值] => 红色
        )

    [3] => 数组
        (
            [目标] => 城市
            [价值] => 巴黎
        )

    [4] => 数组
        (
            [目标] => 类型
            [价值] => 房子
        )

    [6] => 数组
        (
            [目标] => 名称
            [价值] =>
        )

    [7] => 数组
        (
            [目标] => 电子邮件
            [值] => mail@gmail.com
        )

    [9] => 数组
        (
            [目标] => custom2
            [值] => 路径/到/某事
        )

)

我可以通过以下方式做到这一点:

  • 展平阵列
  • 将目标/值分配为新的键/值(如果有欺骗,这会自动覆盖后面的值)
  • 删除任何值为
  • 重建阵列

这感觉不对,我确信使用 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;
}
4

1 回答 1

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,
    );
}
于 2013-01-29T13:22:46.023 回答