-2

可能重复:
比较多维数组中的元素

我的阵列看起来像

Array
(
    [0] => Array
        (
            [event_key] => 1
            [event_id] => 5
            [event_desc] => Test Event 1
        )

    [1] => Array
        (
            [event_key] => 2
            [event_id] => 2
            [event_desc] => Test Event 2
        )

    [2] => Array
        (
            [event_key] => 3
            [event_id] => 5
            [event_desc] => Test Event 3
        )

    [3] => Array
        (
            [event_key] => 4
            [event_id] => 4
            [event_desc] => Test Event 4

        )

    [4] => Array
        (
            [event_key] => 5
            [event_id] => 5
            [event_desc] => Test Event 5

        )

)

如果 event_id 重复,我想删除一个子数组

所以想要的结果是

Array
(
    [0] => Array
        (
            [event_key] => 1
            [event_id] => 5
            [event_desc] => Test Event 1
        )

    [1] => Array
        (
            [event_key] => 2
            [event_id] => 2
            [event_desc] => Test Event 2
        )

    [2] => Array
        (
            [event_key] => 4
            [event_id] => 4
            [event_desc] => Test Event 4

        )


)
4

1 回答 1

1

像这样的东西可以解决问题:

$knownIds = array();
foreach( $myArray AS $key=>$item ) {
  if( array_key_exists($item['event_id'], $knownIds) === true ) {
    unset( $myArray[$key] );
  } else {
    $knownIds[$item['event_id']] = $key;  // value does not matter really here
  }
}
$myArray = array_values($myArray);

$myArray你的源数组在哪里。

于 2012-08-31T11:02:01.367 回答