复制多维数组

时间:2013-01-29 11:24:06

标签: php multidimensional-array deduplication

我有一个相当简单的多维数组,我需要重复数据删除。我还需要删除任何具有值的键,因此在下面的代码中我需要保留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;
}

1 个答案:

答案 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,
    );
}