du0204 2018-02-06 15:57
浏览 26
已采纳

PHP阵列数组独特

I have an array of arrays as following:

$a = array(
  1 => array("sport", "geo"),
  2 => array("sport", "geo", "history"),
  3 => array("geo", "history"),
  4 => array("golf", "sport"),
  ...
);

From that I need to get keys, in such a way so that values are unique. So from that I would need to get something like:

$b = array( 1, 3, 4 );

$a[2] would be cut out, since it has the same values as $a[1], but since $a[2] is not there, $a[3] is fine.

If some values get completely cut out, that's fine. I will have 30+ keys, from which I need to get 10, which have unique values.

Key is a question ID, and values are tags.

I want to get 10 questions, which are different from each other (so that I don't get 10 questions about Sport).

I tried array_unique(), but that just returns this:

Array ( 
  [1] => Array ( 
    [0] => sport 
    [1] => geo 
  )
) 

which doesn't seem to help much.

Can you guys point me towards something that could help me?

I guess I could try to list all possible categories, make that array unique, sort it by random. I would need to preserve Keys, but Keys are unique...

  • 写回答

2条回答 默认 最新

  • doulang5323 2018-02-06 16:07
    关注

    Just iterate through the initial array of questions, every time save the value (array of tags) to another temporary array with checking if actual tags already exists in temporary array - if not add the question to temporary array, if exists go next. Do it until you have 10 questions in your temporary array, if you finish the question array without already having 10 questions - repeat the iteration but this time add other questions even if the tags are repeating - until you have 10.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?