php - how can i count an element if it appears more than once in the same array? -
how can count element if appears more once in same array?
i tried array_count_values, did not work, beacuse got more 1 key , value in array?
this output 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 count how many times same element appears in array , add counted value newly created 'key' called hits in 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 how tried wanted.
foreach ($cooltransactions $key) { $temparrayoverrestaurants[]= $key['restaurant_id']; } $wordsrestaruants = array_count_values($temparrayoverrestaurants); arsort($wordsrestaruants); foreach ($wordsrestaruants $key1 => $value1) { $temprestaurantswithhits[] = array( 'restaurant_id' => $key1, 'hits' => $value1); } foreach ($restlistas $key) { foreach ($temprestaurantswithhits $key1) { if($key['restaurant_id'] === $key1['restaurant_id']) { $nyspisestedsliste[] = array( 'restaurant_id' => $key['restaurant_id'], 'title' => $key['title'], 'hits' => $key1['hits']); } } }
i know noob way want still new @ php..i hope can help
just try associative array:
$input = array( /* input data*/ ); $output = array(); foreach ( $input $item ) { $id = $item['restaurant_id']; if ( !isset($output[$id]) ) { $output[$id] = $item; $output[$id]['hits'] = 1; } else { $output[$id]['hits']++; } }
and if want reset keys, do:
$outputwithoutkeys = array_values($output);
Comments
Post a Comment