-1

具有此数据的以下数组。我怎样才能只向每个人展示一次,然后为每个人展示第一个活动。我可以使用 array_unique() 函数,但这也删除了 Activity 重复项。我只需要删除人员的重复项。

mainArray = array(
'person' => '1', 'Activity' => 'abc', 
'person' => '1', 'Activity' => 'cba',
'person' => '2', 'Activity' => 'abc',
'person' => '2', 'Activity' => 'cba',
'person' => '3', 'Activity' => 'cba');

我想要这个结果:

person 1 - Activity abc
person 2 - Activity abc
person 3 - Activity cba

抱歉,我的数组如下所示:

Array ( [0] => Array ( [Person] => 1 [Activity] => 1 ) 
    [1] => Array ( [Person] => 1 [Activity] => 2 ) 
    [2] => Array ( [Person] => 2 [Activity] => 1 )
4

2 回答 2

1

看看你的数组是不是这样

  $mainArray = Array
   (
     [0] => Array
        (
          [person] => 1
          [Activity] => abc
        )

    [1] => Array
       (
          [person] => 1
          [Activity] => cba
       )

    [2] => Array
       (
          [person] => 2
          [Activity] => abc
       )

    [3] => Array
       (
          [person] => 2
          [Activity] => cba
       )

    [4] => Array
       (
          [person] => 3
          [Activity] => cba
       )
)

那么这里是你的解决方案:

$unique_array = array();
$count = 0;
foreach ($mainArray as $array){
 $insert = false;
 if(!empty($unique_array)){
    foreach($unique_array as $u){

        if($u['person'] != $array['person'])
            $insert = true;
        else
            $insert = false;
    }//End of Foreach
 }else
    $insert = true;
 if($insert){
    $unique_array[$count]['person'] = $array['person'];
    $unique_array[$count]['Activity'] = $array['Activity'];
    $count++;
 }
}
于 2013-06-16T09:42:50.723 回答
0

同一个键不能有两个或多个值;如果两个键相同,如何单独访问一个键的值?

<?php

$mainArray = array(
'person' => '1', 'Activity' => 'abc', 
'person' => '1', 'Activity' => 'cba',
'person' => '2', 'Activity' => 'abc',
'person' => '2', 'Activity' => 'cba',
'person' => '3', 'Activity' => 'cba');

print_r($mainArray);
?>

上面的代码输出如下:

Array ( [person] => 3 [Activity] => cba )
// Only the last unique key-value pair is stored in the array

因此,您可能希望以类似于以下的格式存储值:

$mainArray = array(
    'person'   => array('1',  '1',  '2',  '2',   '3'),
    'Activity' => array('abc','cba','abc','cba','cba')
    );

这也使您更容易获得 的相应值 ( Activity) person

于 2013-06-16T09:36:34.430 回答