F
F
foxxx12342019-05-02 20:59:06
PHP
foxxx1234, 2019-05-02 20:59:06

How to count repetition of array prefix values?

There is an array and I can not find a way to count the number of repetitions for each key. I would be grateful for a hint.

Array
(
    [0] => Array
        (
            [prefix] => 
        )
    [1] => Array
        (
            [prefix] => +57
        )
    [2] => Array
        (
            [prefix] => +268
        )
    [3] => Array
        (
            [prefix] => +972
        )
    [4] => Array
        (
            [prefix] => +972
        )
    [5] => Array
        (
            [prefix] => +33
        )
    [6] => Array
        (
            [prefix] => +33
        )
    [7] => Array
        (
            [prefix] => +972
        )
    [8] => Array
        (
            [prefix] => +509
        )
    [9] => Array
        (
            [prefix] => 
        )
    [10] => Array
        (
            [prefix] => +33
        )
    [11] => Array
        (
            [prefix] => +268
        )
    [12] => Array
        (
            [prefix] => +57
        )
)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Immortal_pony, 2019-05-02
@foxxx1234

$calls = [
    ['prefix' => '+57'],
    ['prefix' => '+268'],
    ['prefix' => '+972'],
    ['prefix' => '+972'],
    ['prefix' => '+33'],
    ['prefix' => '+33'],
    ['prefix' => '+972'],
    ['prefix' => '+509'],
    ['prefix' => ''],
    ['prefix' => '+33'],
    ['prefix' => '+268'],
    ['prefix' => '+57'],
];

function calcPrefixStat($calls) {
    $stat = [];
    foreach($calls as $call) {
        if (!array_key_exists($call['prefix'], $stat)) {
            $stat[$call['prefix']] = 0;
        }
        $stat[$call['prefix']]++;
    }
    
    return $stat;
}

var_dump(calcPrefixStat($calls));
/*
array(6) {
  ["+57"]=>
  int(2)
  ["+268"]=>
  int(2)
  ["+972"]=>
  int(3)
  ["+33"]=>
  int(3)
  ["+509"]=>
  int(1)
  [""]=>
  int(1)
}
*/

S
Stalker_RED, 2019-05-02
@Stalker_RED

Keys in an array cannot be repeated.

$result = array_reduce($calls, 'myStatCounter', []);

function myStatCounter($stat, $call) {
  $prefix = $call['prefix'];
  if (empty($stat[$prefix])) $stat[$prefix] = 0;
  $stat[$prefix]++;
  return $stat;
}

https://ideone.com/tzCGJb

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question