Array
(
[0] => Array
(
[user_id] => 78
[post_id] => 3
[post_user_added_id] => 2
)
[1] => Array
(
[user_id] => 76
[post_id] => 8
[post_user_added_id] => 16
)
[2] => Array
(
[user_id] => 78
[post_id] => 9
[post_user_added_id] => 12
)
[3] => Array
(
[user_id] => 76
[post_id] => 9
[post_user_added_id] => 15
)
[4] => Array
(
[user_id] => 77
[post_id] => 9
[post_user_added_id] => 15
)
)
这里的想法是,当有一个重复的user_id时,它只显示一个?这是预期的结果:
Array
(
[2] => Array
(
[user_id] => 78
[post_id] => 9
[post_user_added_id] => 12
)
[3] => Array
(
[user_id] => 76
[post_id] => 9
[post_user_added_id] => 15
)
[4] => Array
(
[user_id] => 77
[post_id] => 9
[post_user_added_id] => 15
)
)
显示[2]键而不是[0]键或[1]键而不是[3]的原因是因为我想获得重复键的底键。这有点难以解释,但我希望你理解我预期的情景或输出。
非常感谢您的帮助!谢谢! :)
答案 0 :(得分:5)
试试这个:
foreach($arr as $k => $v)
{
foreach($arr as $key => $value)
{
if($k != $key && $v['user_id'] == $value['user_id'])
{
unset($arr[$k]);
}
}
}
print_r($arr);
答案 1 :(得分:1)
尝试
$array = Array (
"0" => Array (
"user_id" => 78,
"post_id" => 3,
"post_user_added_id" => 2
),
"1" => Array (
"user_id" => 76,
"post_id" => 8,
"post_user_added_id" => 16
),
"2" => Array (
"user_id" => 78,
"post_id" => 9,
"post_user_added_id" => 12
),
"3" => Array (
"user_id" => 76,
"post_id" => 9,
"post_user_added_id" => 15
),
"4" => Array (
"user_id" => 77,
"post_id" => 9,
"post_user_added_id" => 15
)
);
$keys = array ();
// Get Position
foreach ( $array as $key => $value ) {
$keys [$value ['user_id']] = $key;
}
// Remove Duplicate
foreach ( $array as $key => $value ) {
if (! in_array ( $key, $keys )) {
unset ( $array [$key] );
}
}
var_dump ( $array );
输出
array
2 =>
array
'user_id' => int 78
'post_id' => int 9
'post_user_added_id' => int 12
3 =>
array
'user_id' => int 76
'post_id' => int 9
'post_user_added_id' => int 15
4 =>
array
'user_id' => int 77
'post_id' => int 9
'post_user_added_id' => int 15
答案 2 :(得分:0)
您可以使用foreach循环覆盖user_id。我觉得这样的事情应该有用
$new = array();
foreach ($array as $value)
{
$new[$value['user_id']] = $value;
}
print_r($new);
答案 3 :(得分:0)
以下对我有用,用于清洁以下物品:
$arr = array(
array("ID"=>"234"),
array("ID"=>"235"),
array("ID"=>"236"),
array("ID"=>"236"),
array("ID"=>"234"),
);
代码:
for ($i=0; $i <count($arr) ; $i++) {
$distinct_id = $arr[$i]["ID"]; // this is the ID for which we want to eliminate the duplicates
$position = $i; // position of that array (so we ignore it)
$unset_arr = array(); // these duplicate entries will be removed
// Collect list of duplicates to remove
for ($y=0; $y <count($arr) ; $y++) {
// Skip the position of the array that we're checking (we want to remove duplicate not the original)
if($y == $position)
continue;
// If found remove and reset keys
if($arr[$y]["ID"] == $distinct_id) {
$unset_arr[] = $y;
}
}
// Remove IDs collected in the loop above
foreach ($unset_arr as $k) {
unset($arr[$k]);
}
// Reset keys
$arr = array_values($arr);
}
(如果要删除较新的副本而不是较旧的副本,则反转数组)