如果元素在同一个数组中出现多次,我该如何计算?

时间:2013-03-04 11:31:40

标签: php arrays

如果元素在同一个数组中出现多次,我如何计算它?

我已经尝试过使用array_count_values,但它没有用,是不是因为我的数组中有多个键和值?

这是我的数组输出(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 ) 
)

我希望它计算同一个元素在我的数组中出现的次数,然后将计数值添加到我在新阵列中创建的名为hits的“key”中。

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) 
)

这就是我试图做我想做的事情。

     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']);   
        }
    }
}

我知道这可能是我想做的事情的菜鸟方式,但我仍然是新的PHP ..我希望你能帮忙

1 个答案:

答案 0 :(得分:1)

尝试使用关联数组:

$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']++;
  }
}

如果您想重置密钥,请执行以下操作:

$outputWithoutKeys = array_values($output);