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条)

报告相同问题?