Skip to content
Advertisement

Compare values from a single array with multiple series of arrays, then echo the result

With the following script I am able to calculate the frequency of every number from 10 different arrays, then echoes the result sorting the numbers in frequency classes (ex. values that appear one time : x, y, z , values that appear two times : a, b, c, ….etc.)

JavaScript

My problem : I would like to calculate the frequency and echo the result of an extra array of numbers that should be compared with the actual set of arrays of my script.

For example : If I have

JavaScript

i would like to

  • check how many times those numbers appear in the $set1 to $set10 arrays
  • echo the result sorting the numbers in frequency classes like now.

but I don’t understand how to compare the $extraset (i am a real newbie..!)

thanks for your help !

Advertisement

Answer

You can think of the problem as a conversion problem. You are converting numbers to their frequency and vice versa. array_count_values sets up a table of conversions as an array. The keys of the array, gives the numbers to convert and their values their frequency.

So start off with building up the merged arrays:

JavaScript

Next set up the conversion table:

JavaScript

Then set up the inverse lookup of this table (keys are counts, values are numbers):

JavaScript

Sort this, so the keys (counts) are ascending for display purposes:

JavaScript

And display them:

JavaScript

This method is more general and flexible than the one you gave.

Next we take the $extraset array and loop through to find the frequency of each element and display it:

JavaScript

Note the use of of the null coalescing operator ?? just in case we can’t find the number in the frequency list.

EDIT

You could improve on the way the sets are handled, by pushing each new set into an array and then merging (ideally you would put this in a function):

JavaScript

That allows you to have an indexed set of arrays ($sets), the ones with higher indexes are newer.

You can then search the $sets array in reverse to find the most recent instance of a number:

JavaScript

You need to fixup the $index because reversing the array re-indexes it (the keys are not kept).

You need break so that as soon as you find a value, you move on to the next value.

I’ll leave it up to you how you handle elements which are not found.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement