0
Array ( 
 [0] => Array ( [0] => b [1] => d)  
 [1] => Array ( [0] => c [1] => a) 
 [2] => Array ( [0] => b [1] => d)
 [3] => Array ( [0] => a [1] => d)
 [4] => Array ( [0] => c )
 [5] => Array ( [0] => a [1] => d [2] => e)
 [6] => Array ( [0] => d [1] => b)
 )

I would like to perform a count on unique inner arrays, so I can get a count similar to:

2 of b,d

1 of c,a

1 of a,d

1 of c

1 of a,d,e

1 of d,b

I looked at "implode" function, but I only get a listing of all values in the inner arrays instead of a count.

foreach ($result_array as &$pair) 
    {
    $pair = implode(', ', $pair);
    }

1 Answer 1

2

You were so close... Try this:

$original = array ( 
    array ('b', 'd'),  
    array ('c', 'a'), 
    array ('b', 'd'),
    array ('a', 'd'),
    array ('c'),
    array ('a', 'd', 'e'),
    array ('d', 'b')
);

$result = array();

foreach ($original as $part) {

    $key = implode(', ', $part);

    if( ! array_key_exists ($key, $result)) {
        $result[$key] = 0;
    }

    $result[$key] = $result[$key] + 1;
}

foreach ($result as $key => $value) {
    echo "$value of {$key}<br/>";   
}

Output:

2 of b, d
1 of c, a
1 of a, d
1 of c
1 of a, d, e
1 of d, b

Sign up to request clarification or add additional context in comments.

7 Comments

I would not call that even close. Something with "implode" but that is about it... :( I think I had about 25% of it... appreciate it!
Paul - I am wondering, now that we have an array with these values, it is possible to manipulate the letters inside the the $key (ie. A, B, C, D, E)? If no, what if I swapped what the $key and $value variables held? I am thinking of say, adding all these arrays' values where A is the first in the sequence. Possible?
Can you give an example or the output of the result that you expect? I'm not absolutely sure what you mean.
Right now in the $result array, the key stores the unique combination of letters, and the value for that key is the total of times it appears. I was hoping to swap these two so that the key stores the total of instances, and the $key will contain the letter pattern. I am hoping that having the letter patters as values (and not keys), to allow me to do some math on each of the letter (ie. remove all instances of letter "b" let's say, or add keys where letter "a" appears first in a value - not sure if that is possible), etc.
I am going to ask another question (in a new thread), non-code, but mostly pertaining to the approach/logic and methods.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.