0

I am fetching some data from the db and then push them to an array. I need to find the count of some strings and print out the result (count) in an efficient way:

Array
(
    [0] => q1-1,q2-2,q3-2,q4-1,q5-2,q6-3,q7-1,q8-4,
    [1] => q1-1,q2-2,q3-1,q4-3,q5-3,q6-3,q7-2,q8-1,
    [2] => q1-1,q2-1,q3-1,q4-1,q5-1,q6-2,q7-2,q8-2,
    [3] => q1-3,q2-1,q3-1,q4-1,q5-2,q6-3,q7-1,q8-1,
    [4] => q1-2,q2-2,q3-3,q4-1,q5-3,q6-3,q7-1,q8-1,
    [5] => q1-1,q2-2,q3-3,q4-1,q5-2,q6-3,q7-1,q8-1,
    [6] => q1-3,q2-1,q3-1,q4-3,q5-2,q6-3,q7-2,q8-4,
    [7] => q1-2,q2-2,q3-3,q4-1,q5-2,q6-5,q7-1,q8-1,
    [8] => q1-1,q2-1,q3-2,q4-3,q5-3,q6-5,q7-1,q8-1,
    [9] => q1-2,q2-1,q3-1,q4-1,q5-3,q6-3,q7-1,q8-1,
    [10] => q1-3,q2-2,q3-3,q4-3,q5-4,q6-3,q7-1,q8-1,
    ...
)

Sample data is above.

I need to know how many occurences of q1-1, q1-2 ... q8-4 is in the array and print out readable version. Ex. The are 23: q1-1, 412: q1-2 and so on.

I was going to create an array of each string that needs to be searched that iterate through the array. For every result increment the resultVariable for that string but I'm not sure if that's the best way.

Suggestions?

2
  • Would it not be cleaner to do this with the initial database query? Commented Dec 3, 2012 at 16:58
  • I'd say that array example does not implement a valid array in php. Commented Dec 3, 2012 at 17:02

2 Answers 2

2

Pretty simple, loop on your array, create sub arrays, and create a counter array:

$counts = array () ;
foreach ( $your_array as $row ) {
    $sub = explode(',', $row);
    foreach ( $sub as $subval ) {
        if ( array_key_exists ( $subval, $counts ) ) {
            $counts[$subval] ++ ;
        } else {
            $counts[$subval] = 1 ;
        }
    }
}

Here is $counts:

Array (
    'q1-1' => 23,
    'q1-2' => 9,
    // and so on....
);
Sign up to request clarification or add additional context in comments.

Comments

0

Try:

$arr = array(...); //your array 
$count = array();       
foreach($arr as $v) {
 $substr = explode(',', $v); 
 foreach($substr as $m) {   
 if(strstr($v, $m) !== FALSE)
  $count[$m]++; 
 }    
}

Printing the counts,

foreach($count as $k => $v)
 echo "Count for '$k': ". $v;

2 Comments

Not a portable solution, you would have to manually test any 'qx-x' possibility..
Sorry your code seems pretty weird: strstr($v, $substr) will ALWAYS be true! and you are assigning an arry-typed key to the counts array. Or am I wrong?

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.