Logic and Syntax- looking for a shortcut- convert 2D array to a 1D array with no repetitive values

65 Views Asked by At

I have an array of arrays of numbers. This is my 2D array. eg:
[ [2,5,8] , [4,8,11,12] , [3,4,7] ]
I want to convert this into a single array i.e. my 1D array to have each of these values with a tally count.
This is probably better as an associative array. eg:
[ 2=>1, 3=>1, 4=>2, 5=>1, 7=>1, 8=>2, 11=>1, 12=>1]

I am more interested in the logic, but if I can get it in PHP all the more better.
The logic is the main thing that I need because the way I see it is very long and requires:
1. joining all the arrays into 1 huge array.
2. sorting everything in the array (only useful if it is numbers or anything that can be compared)
3. then analyzing this array from one end to the other while maintaining a smaller array with the tally.

I know my logic sounds pretty nice, but I'm open to more answers. :P

1

There are 1 best solutions below

0
On

This is going to be mostly logic, but I'll throw in some PHP: it should be clear enough.

$newDestinationArray
foreach (in 2D SourceArray)
    foreach $element (in 1D SourceArray)
        if !array_key_exists($element, $newDestinatioArray)
            $newDestinationArray[] = $element;   # Add new key to newArray
            $newDestinationArray[$element] = 1;  # Set value of new key to 1
        else 
            $newDestinationArray[$element] += 1; # Update existing key's value

I hope this helps!