2

I have an array that looks like this:

Array(
[172.17.0.2] => Array
    (
        [okok] => 1
    )

[172.17.0.1] => Array
    (
        [wp] => 3
        [ojopj] => 1
        [opjopj] => 1
    )

)

I need to be able to count the 2nd level contents and then sort the top level arrays based on these totals.

So for example my resultant array would look something like this:

Array(
  [172.17.0.2] => 1
  [172.17.0.1] => 5
)

I then ideally want to sort by descending order and show only the top 5 results.

At present my code consists of the following:

foreach ($iplog as $ip => $arr) {
    foreach ($arr as $user => $count) {
        $count_desc = $count_desc + $count;
    }
    $output .= $count_desc;
    $output .= '</span><hr style="width:100%">';
}

However, this doesn't take care of any sorting or limiting the results to the top 5. Based on the code I have so far, I can only envisage create more for loops to build a new array, sort it and so on.

Is there a much more efficient way to achieve the results I need?

4
  • 3
    @EliasSoares Except there is a complete derth of Javascrip tags on this question Commented Jun 27, 2019 at 15:55
  • 1
    You say "count", but it appears you meant "sum". Commented Jun 27, 2019 at 15:56
  • @Barmar Indeed I do. Commented Jun 27, 2019 at 16:13
  • @RiggsFolly you're right. I selected wrong question to suggest duplicate. But I'm pretty sure that there's tons of questions like this on SO Commented Jun 27, 2019 at 16:18

2 Answers 2

4

Just map to a function to sum the inner arrays, sort and slice the first 5:

$result = array_map('array_sum', $iplog);
arsort($result);
$top5 = array_slice($result, 0, 5, true);
Sign up to request clarification or add additional context in comments.

1 Comment

You also need to call asort() after.
3

Easy enough in a few lines:

$x = array_map('array_sum', $iplog); // sum the values
arsort($x, SORT_NUMERIC); // reverse sort
$y = array_slice($x, 0, 5, true); // top 5

Importantly, each of these transformations preserves the keys. In PHP, there are array functions that do, and functions that do not, preserve keys. Being aware of this saves some grief.

Side note, if an IP has an empty array, that's treated as zero.

1 Comment

That seems to be working great! I can't test the limit to 5 yet but I have no reason to think it wont work. Thanks for the compact solution.

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.