我有以下多维数组:
<?php
$array = array(
array('first' => 1, 'second' => 1),
array('first' => 1, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1),
array('first' => 3, 'second' => 1),
array('first' => 3, 'second' => 1));
如何删除重复的first
值?同时保留重复的second
值。
处理后的数组应为:
array(
array('first' => 1, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1));
答案 0 :(得分:1)
代码:
$array = array(
array('first' => 1, 'second' => 1),
array('first' => 1, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1),
array('first' => 3, 'second' => 1)
);
$temp = array();
$new = array();
foreach($array as $value)
{
if(!in_array($value['first'],$temp))
{
$temp[] = $value['first'];
$new[] = $value;
}
}
现在$new
包含以下内容:
array(
array('first' => 1, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1),
);
答案 1 :(得分:0)
您必须执行一些foreach
循环并自行重新组装阵列。查看PHP的array_unique()。
答案 2 :(得分:0)
这将删除重复的数组:
$array = array_map('unserialize', array_unique(array_map('serialize', $array)));
密钥仍然相同,因此您可能需要修复它们。
答案 3 :(得分:0)
如果数组是这样的话
$array = array(
array('first' => 1, 'second' => 1),
array('first' => 1, 'second' => 1),
array('first' => 1, 'second' => 12),
array('first' => 2, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1),
array('first' => 3, 'second' => 1)
);
$temp = array();
$new = array();
您希望新数组$ new包含以下内容:
array(
array('first' => 1, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1),
);
或
array(
array('first' => 1, 'second' => 1),
array('first' => 1, 'second' => 12),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1),
);