• 0
Votes
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /var/www/html/cnasolution/application/views/question.php
Line: 191
Function: _error_handler

File: /var/www/html/cnasolution/application/controllers/Questions.php
Line: 419
Function: view

File: /var/www/html/cnasolution/index.php
Line: 315
Function: require_once

I have an array that looks like this:

[[["Sports", "Soccer"], 2], [["eSports"], 1], [["Sports", "Soccer"], 3]] 

In any element of the outermost array, the first element (the array) are the list of categories. The second element is the program.id this array of categories comes from.

So, taking the first element in the above array - ["Sports", "Soccer"] is the array of categories for program_id: 2.

How do I count the instances of the category array duplicates? In the above case, what I want is something like this:

["Sports", "Soccer"] => Occurs 2 times, with Program Ids: 2 & 3 ["eSports"] => Occurs 1 time, with Program Id: 1 

How do I do that efficiently?

Download script demo [LINK]
Download script demo [LINK 2] Download script demo [LINK 2]

How about this?

arr = [[["Sports", "Soccer"], 2], [["eSports"], 1], [["Sports", "Soccer"], 3]] count = {} arr.each do |el|   el[0].each do |category|     count[category] ||= []     count[category] << el[1]   end end  count.each do |category, ids|   puts "#{category} occurs #{ids.count} times, with Program Ids: #{ids.join(' & ')}" end 

output

Sports occurs 2 times, with Program Ids: 2 & 3 Soccer occurs 2 times, with Program Ids: 2 & 3 eSports occurs 1 times, with Program Ids: 1 
see demo
  • 0
Reply Report
grouped = array.group_by { |s, id| s }.transform_values { |v| v.map(&:last) }  => { ["Sports", "Soccer"] => [2, 3],       ["eSports"]          => [1] } 

To use it:

grouped.each { |k,v|    puts "[#{k.join(', ')}] occurs #{v.length} time(s) with ID: #{v.join(' and ')}"  }  [Sports, Soccer] occurs 2 time(s) with ID: 2 and 3 [eSports] occurs 1 time(s) with ID: 1 
demo
  • 0
Reply Report