Skip to content
Advertisement

get count of duplicated next value from array and store it to other array

I’m really confused to this logic and seems I can’t figure it out, basically what i want is to store count if there is same value in next and next element store it on array then the rest store

This is my code

      $json = '[{
            "fight_declaration": "1"
        },
        {
            "fight_declaration": "2"
        },
        {
            "fight_declaration": "2"
        },
        {
            "fight_declaration": "1"
        },
        {
            "fight_declaration": "3"
        }
        ]';

    $data = json_decode($json,true);
    $count = 0;
    $array = [];
    while ($current = current($data) )
    {
        $next = next($data);
        if (false !== $next && $next['fight_declaration'] == $current['fight_declaration'])
        {
        $count++;
        $array[]['count'] = $count;
        }
    }

    print_r($count);

What i want output is like this

    [{
        "count": 1
    },
    {
        "count": 2
    },
    {
        "count": 1
    },
     {
        "count": 1
    }
    ]

In my output i want fight_declaration has same value now i want to count it and store it on array

Thanks

Advertisement

Answer

You could do it like this:

$counts = [];
foreach ($data as $entry) {
    if (!isset($previous)) {
        $currentCount = ['count' => 1];
    } elseif ($entry->fight_declaration === $previous->fight_declaration) {
        $currentCount['count']++;
    } else {
        $counts[] = $currentCount;
        $currentCount = ['count' => 1];
    }
    $previous = $entry;
}
if (isset($currentCount)) {
    $counts[] = $currentCount;
}

This basically stores the current count in $currentCount and, either:

  • sets it to 1 if it’s the very first value,
  • increments it if it’s the same as the previous,
  • adds it to the list of counts and resets it to 1 otherwise,
  • stores the last count into the list at the end.

Demo

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement