Count how many times each element appeared with another element in an array

0

I have these arrays as reference:

$a_controle = array ('A','B','C','D','E','F');

var_dump($array_final) =>
array (size=5)
  0 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string 'B' (length=1)
      2 => string 'C' (length=1)
  1 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string 'B' (length=1)
      2 => string 'D' (length=1)
  2 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string 'C' (length=1)
      2 => string 'E' (length=1)
  3 => 
    array (size=3)
      0 => string 'D' (length=1)
      1 => string 'E' (length=1)
      2 => string 'F' (length=1)
  4 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string 'B' (length=1)
      2 => string 'P' (length=1)

How can I count how many times each element of $a_controle exited together with another in $array_final ?

For example:

  • A appeared with B 3 times
  • A appeared with C 2 times
  • A appeared with D 1 times
  • A appeared with E 1 time
  • A appeared with F 0 times

A verification is passed to the next element of $a_controle (element B):

  • B appeared with C 1 time
  • B appeared with D 1 time
  • B appeared with E 0 times
  • B appeared with F 0 times

B verification is passed to the next element of $a_controle (element C).

The C check passes to the next element of $a_controle (element D).

The D check passes to the next element of $a_controle (element E).

E verification is passed to the next element of $a_controle (element F).

So successively for an array of unknown size. Is it possible?

    
asked by anonymous 22.11.2017 / 01:13

1 answer

1

You can use foreach to get to the sub array to parse, and then use two for to check each element in your neighbors:

$a_controle = Array('A','B','C','D','E','F');
$array_final = Array(
    Array("A","B","C"),
    Array("A","B","D"),
    Array("A","C","E"),
    Array("D","E","F"),
    Array("A","B","P")
); 

$apareceu_com = Array();

foreach ($array_final as $sub_array_final){
    for ($i = 0; $i < count($sub_array_final); ++$i){
        for ($j = 0; $j < count($sub_array_final); ++$j){
            $elem1 = $sub_array_final[$i];
            $elem2 = $sub_array_final[$j];

            if ($i != $j){ //se não é o proprio elemento
                if (isset($apareceu_com[$elem1][$elem2])){
                    $apareceu_com[$elem1][$elem2]++;
                }
                else {
                    $apareceu_com[$elem1][$elem2] = 1;
                }
            }
        }
    }
}

print_r($apareceu_com);

Output:

Array
(
[A] => Array
    (
        [B] => 3
        [C] => 2
        [D] => 1
        [E] => 1
        [P] => 1
    )

[B] => Array
    (
        [A] => 3
        [C] => 1
        [D] => 1
        [P] => 1
    )
...

Example on Ideone

    
22.11.2017 / 01:34