0

I have this array:

Array
(
    [LEVEL1] => Array
        (
            [0] => 18
            [1] => 12
            [2] => 16
            [3] => 12
            [4] => 12
        )

    [LEVEL2] => Array
        (
            [0] => 16
            [1] => 18
            [2] => 19
            [3] => 19
            [4] => 16
        )

)

I would like to get subtotals sorted by key.

Array
(
    [LEVEL1] => Array
        (
            [12] => 3
            [16] => 1
            [18] => 1
        )

    [LEVEL2] => Array
        (
            [19] => 2
            [16] => 2 (rectification on the sorting)
            [18] => 1
        )

)

I tried many functions I found in php.net, but didn't even manage to sort it.

I can't get passed the first level.

Thanks Sebastian

2 Answers 2

3

Use array_map() & array_count_values(). Example:

$your_arr = Array(
    'LEVEL1' => Array(18,12,16,12,12),
    'LEVEL2' => Array(16,18,19,19,16,)
);

$keys = array_keys($your_arr);
$result = array_combine($keys, array_map(function($v, $k){
    $values = array_count_values($v);
    ($k == 'LEVEL1') ?  ksort($values) : krsort($values);
    return $values;
}, $your_arr, $keys));

print '<pre>';
print_r($result);
print '</pre>';

Output:

Array
(
    [LEVEL1] => Array
        (
            [12] => 3
            [16] => 1
            [18] => 1
        )

    [LEVEL2] => Array
        (
            [19] => 2
            [18] => 1
            [16] => 2
        )
)
Sign up to request clarification or add additional context in comments.

3 Comments

I always think, that array_map loss array keys... Thanks :)
Your array isn't sorted like OP wanted. So sort it and your answer is fine!
Sorry, I made a mistake in my example. it had to be sorted by DESC based on Counts. I rectified it. So I changed the second krsort for arsort, and that works perfectly. Thanks to both.
2

This should work for you:

<?php

    $array = array (
            "LEVEL1" => array (18, 12, 16, 12, 12),
            "LEVEL2" => array (16, 18, 19, 19, 16)
        );

    $newarray = array();

    foreach($array as $k => $v) {
        $newarray[$k] = array_count_values($array[$k]);
        if($k == "LEVEL1")
            ksort($newarray[$k]);
        elseif($k == "LEVEL2")
            krsort($newarray[$k]);
    }

    print_r($newarray);

?>

Output:

Array
(
    [LEVEL1] => Array
        (
            [12] => 3
            [16] => 1
            [18] => 1
        )

    [LEVEL2] => Array
        (
            [19] => 2
            [18] => 1
            [16] => 2
        )

)

Comments

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.