4

I have the following array:

Array
(
[0] => Array
    (
        [0] => 2015-07-18
        [1] => 22 SSH
    )

[1] => Array
    (
        [0] => 2015-07-18
        [1] => 80 HTTP
    )

[2] => Array
    (
        [0] => 2015-07-18
        [1] => 3389 Remote Desktop
    )

[3] => Array
    (
        [0] => 2015-07-19
        [1] => 3389 Remote Desktop
    )

[4] => Array
    (
        [0] => 2015-07-19
        [1] => 3389 Remote Desktop
    )
)

and need the data counted by day and number of occurrences in the following format:

array(4) {
  [0]=>
  array(1) {
    [0]=> "3389 Remote Desktop"
    [1]=> "1,2"
  }
  [1]=>
  array(1) {
    [0]=> "22 SSH"
    [1]=> "1,0"
  }
  [2]=>
  array(1) {
    [0]=> "80 HTTP"
    [1]=> "1,0"
  }
}

How can I achieve this? I am able to count all occurences but not grouped by date and type like this:

$counts = array();
foreach( $stack_stats_timeline as $value) {
    foreach( $value as $k => $v) {
        if( !isset( $counts[$k])) $counts[$k] = array();
        if( !isset( $counts[$k][$v])) $counts[$k][$v] = 0;
        $counts[$k][$v] += 1;
    }
}      
2
  • where does the source array come from? If it came out of the database then you should write an other query. Commented Jul 26, 2015 at 10:33
  • I generate it with PHP myself. Please give me a solution with an other source array if possible. I can adjust the source array if needed. Commented Jul 26, 2015 at 10:35

1 Answer 1

1

I think this'll help you to get it work

$result = array();
$count = 1;
foreach ($arr as $key => &$value) {
    $hash = $value[1];
    $result[$hash][0] = $value[1];
    $result[$hash][1][$value[0]] = (isset($result[$hash][1][$value[0]])) ? $count + 1 : $count;
}
print_r(array_values($result));
Sign up to request clarification or add additional context in comments.

2 Comments

that works great! I run however in an other problem now: when the array keys of each occurence is the date it does not work for my purposes. How can I reset the array keys to default after I sorted them by date?
Just set your $hash into $value[0] and that's it

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.