Zaz
Zaz

Reputation: 1102

how can i count an element if it appears more than once in the same array?

how can i count an element if it appears more than once in the same array?

I already tried with array_count_values, but it did not work, is it beacuse i got more than one key and value in my array?

This is my output from my array (restlist)

Array ( 
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla) 
[1] => Array ( [restaurant_id] => 32144 [title] => test5) 
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 ) 
[3] => Array ( [restaurant_id] => 32144 [title] => test5) 
[4] => Array ( [restaurant_id] => 42154 [title] => blabla2 ) 
)

I want it to count how many times the same element appears in my array and then add the counted value to my newly created 'key' called hits in the same array.

Array ( 
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla [hits] => 1) 
[1] => Array ( [restaurant_id] => 32144 [title] => test5 [hits] => 2) 
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 [hits] => 2) 
)

This is how i tried to do what i wanted.

     foreach ($cooltransactions as $key) 
        {
            $tempArrayOverRestaurants[]= $key['restaurant_id'];
        }

        $wordsRestaruants = array_count_values($tempArrayOverRestaurants);
        arsort($wordsRestaruants);

    foreach ($wordsRestaruants as $key1 => $value1)
         {

                    $temprestaurantswithhits[] = array(
                        'restaurant_id' => $key1,
                        'hits' => $value1);     
        }

foreach ($restlistas $key) 
{
    foreach ($temprestaurantswithhits as $key1) 
    {
        if($key['restaurant_id'] === $key1['restaurant_id'])
        {
                      $nyspisestedsliste[] = array(
                        'restaurant_id' => $key['restaurant_id'], 
                        'title' => $key['title'],
                        'hits' => $key1['hits']);   
        }
    }
}

I know this is probably a noob way to do what i want but i am still new at php..I hope you can help

Upvotes: 0

Views: 794

Answers (1)

hsz
hsz

Reputation: 152216

Just try with associative array:

$input  = array( /* your input data*/ );
$output = array();

foreach ( $input as $item ) {
  $id = $item['restaurant_id'];

  if ( !isset($output[$id]) ) {
    $output[$id] = $item;
    $output[$id]['hits'] = 1;
  } else {
    $output[$id]['hits']++;
  }
}

And if you want to reset keys, do:

$outputWithoutKeys = array_values($output);

Upvotes: 1

Related Questions