-1

我的数组在下面给出。其中包含多个数组。

Array
(
[0] => Array
    (
        [user_id] => 1
        [name] => name1
    )

[1] => Array
    (
        [user_id] => 2
        [name] => name2
    )
[2] => Array
    (
        [user_id] => 2
        [name] => name2
    )
[3] => Array
    (
        [user_id] => 3
        [name] => name3
    )

)<br/>

我需要有不止一次出现的数组。在这种情况下

Array
(
    [user_id] => 2
    [name] => name2
)
4

4 回答 4

0

尝试这个。

function get_multi_occur($my_array)
{
    foreach ($my_array as $id => $a) {
        $key = $a[user_id] . $a[name];
        if ($s[$key]['cnt'] == 0) {
            $s[$key]['cnt'] = 1;
            $s[$key]['id'] = $id;
        } else {
            $s[$key]['cnt']++;
        }
    }
    foreach ($s as $r) {
        if ($r['cnt'] >= 2) {
            $ret[] = $my_array[$r[id]];
        }
    }
    return $ret;
}
于 2012-11-05T08:18:58.017 回答
0

创建一个新数组来存储具有相同值的数据。

试试这个代码:

$array_existing = array();

$ctr = 0;
foreach ($first_array as $key => $first) :
    foreach ($second_array as $keytwo => $second) : 
        if ($first['user_id'] == $second['user_id'] && $first['name'] == $second['name']) {
            $array_existing[$ctr]['user_id'] = $first['user_id'];
            $array_existing[$ctr]['name'] = $first['name'];
            $array_existing[$ctr]['first_index'] = $key;
            $array_existing[$ctr]['second_index'] = $keytwo;
            $ctr++;
        }
    endforeach;
endforeach;

var_dump($array_existing);
于 2012-11-05T08:59:45.083 回答
0
foreach ($array as $key_1=>$sub_array_1)
{
   foreach ($array as $key_2=>$sub_array_2)
   {
      if ($sub_array_1 == $sub_array_2 && 
          $key_1 != $key_2)//prevent to compare same sub arrays
      print_r($sub_array_1);
   }
}

像这样的东西

于 2012-11-05T07:58:54.380 回答
0

你可以试试

$array = Array(
        "0" => Array("user_id" => 1,"name" => "name1"),
        "1" => Array("user_id" => 2,"name" => "name2"),
        "2" => Array("user_id" => 2,"name" => "name2"),
        "3" => Array("user_id" => 3,"name" => "name3"));

$d = $s = array();
array_map(function ($v) use(&$d, &$s) {
    array_key_exists($v['user_id'], $s) && ! array_key_exists($v['user_id'], $d) ? $d[$v['user_id']] = $v : $s[$v['user_id']] = $v;
}, $array);

var_dump($d);

输出

array
  2 => 
    array
      'user_id' => int 2
      'name' => string 'name2' (length=5)
于 2012-11-05T08:06:48.553 回答