0

I want to count the same values of DIAGNOSA at the array:

Array
(
[0] => Array
    (
        [NIK_PASIEN] => 6005
        [DIAGNOSA] => ["Hipertensi","ISPA"]
    )

[1] => Array
    (
        [NIK_PASIEN] => 6163
        [DIAGNOSA] => ["ISPA"]
    )
[2] => Array
    (
        [NIK_PASIEN] => 5853
        [DIAGNOSA] => ["Hipertensi","ISPA","Vertigo"]
    )

[3] => Array
    (
        [NIK_PASIEN] => 5613
        [DIAGNOSA] => ["Vertigo"]
    )
)

How to make it will convert to array like following?

Array
(
[0] => Array
    (
        [DIAGNOSA] => ISPA
        [COUNT] => 3
    )

[1] => Array
    (
        [DIAGNOSA] => Hipertensi
        [COUNT] => 2
    )
[2] => Array
    (
        [DIAGNOSA] => Vertigo
        [COUNT] => 2
    )
)

and I will display it in the following table:

DIAGNOSA COUNT
ISPA 3
Hipertensi 2
Vertigo 2

How should I make it?

1 Answer 1

1

try this piece of code!

$array = [
            ['NIK_PASIEN'=>6005,'DIAGNOSA'=>["Hipertensi","ISPA"]],
            ['NIK_PASIEN'=>6163,'DIAGNOSA'=>["ISPA"]],
            ['NIK_PASIEN'=>5853,'DIAGNOSA'=>["Hipertensi","ISPA","Vertigo"]],
            ['NIK_PASIEN'=>5613,'DIAGNOSA'=>["Vertigo"]],
        ];

$detailed = [];
    foreach ($array as $ar) {
        foreach ($ar['DIAGNOSA'] as $key) {
            $original_key = array_search($key, array_column($detailed, 'DIAGNOSA'), true);
            if ($original_key !== false) {
                $detailed[$original_key]['COUNT'] += 1;
            } else {
                $temp['DIAGNOSA'] = $key;
                $temp['COUNT'] = 1;
                $detailed[] = $temp;
            }
        }
    }

the result will be in detailed array

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

2 Comments

Thank you so much @Sterko , you are so great.
@AsyahSinaga you are welcome, mark as correct this answer!

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.