Rate array based on array value - php

occurrence of A----5 times
occurrence of B----7 times
occurrence of C----6 times
($total['A']=5;
$total['B']=7;
$total['C']=6;)
I need to rate each based on their occurrence as follows,
$rating['A']=3;
$rating['B']=1;//most occurrence will get rate 1.
$rating['C']=2;

asort(&$total);
$rating = 1;
foreach (array_reverse($total) as $key => $val)
$total[$key] = $rating++;

You could also try using the array functions like sorting the values first and get keys of the sorted array and then create another array with the extracted keys as values. Now you get the same array with their rankings, except that you have '0' rank first as arrays start with an index 0.
May be you could pad an additional value with '0' an then finally remove it.
Something like this,
$total['A']=5;
$total['B']=7;
$total['C']=6;
$total[0]=0;
asort($total);
$total = array_slice(array_flip(array_keys($total)),1);
Or if you don't like to pad an extra value, you can try it this way. Create an array with the keys and the count of the sorted array.
asort($total);
$total = array_combine(array_keys($total),range(1, count($total)));
This might be a quick and easy way of doing. Hope this helps.

Related

Explode Array and Show 4 random items at a time with Shuffle

I am trying to explode an array and then shuffle 4 items at a time so that each array appears in random order.
It half works but on refresh sometimes it shows only 2 or 3 arrays not 4. Is there an easy workaround for it?
Thanks in advance.
$siteswith = $row['siteswith'];
$array = explode(',', $siteswith);
shuffle($array);
foreach(array_slice($array, 0, 4) as $item ){
}
It seems that $array does not have enough items that the slice function can "slice" from. Please check if your input string $row['siteswith'] always provide 4 or more comma separated values.
Depending what the code is later used for, you could also use array_rand() to pick n random elements from the list
$siteswith = $row['siteswith'];
$array = explode(',', $siteswith);
foreach(array_rand($array, 4) as $item ){
...
}
This will also prevent mutating your origin array (other than array_shift will do) which avoids unexpected behaviour.
Please be aware that you'll receive an exception when the array size is smaller than the requested amount of random elements.

How can i count all the elements of this whole php array?

$players = array(
array('Lionel Messi', 'Luis Suarez', 'Neymar Jr'),
array('Ivan Rakitic', 'Andres Iniesta', 'Sergio Busquets'),
array('Gerrard Pique', 'Mascherano', 'Denis Suarez', 'Jordi Alba'),
array('MATS'),
array('Arda Turan', 'Munir El Hadadi', 'Umtiti')
);
Now i am trying to echo the number of all the elements within the boundary of this array $players. For example, there are 3 elements in the first, 3 in the second. There are 4 elements in the third, 1 element in the 4th and 3 elements in the last one. Altogether these elements are 14 elements. Now i want to display 'Total Players: 14'. I can show the number of categories (5) using count() function but can't count the total elements(14). I tried different approaches but couldn't succeed.
count() should be able to do this for you directly, using the COUNT_RECURSIVE flag:
$playerCount = count($players, COUNT_RECURSIVE) - count($players);
// $playerCount is now equal to 14
The subtraction of the normal count is because counting recursively adds the keys of the outer array in to the sum of elements, which just needs to be subtracted from the recursive count.
The native count() method can do that.
$count = count($players, COUNT_RECURSIVE) - count($players);
Because the recursive count will also count the number of $player groups you have, you have to subtract that number from the recursive count.
From the php documentation for count:
If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.
One other way, pretty self-explanatory:
$count = array_sum(array_map('count', $players));
$count=0;
foreach($players as $row) $count+=count($row);
$count is now 14.
Live demo
You can use:
count($array, COUNT_RECURSIVE);
check count manual
Declare a variable initialised to 0 to accumulate the number of elements. Then, iterate the first array (which contains the other arrays), and for each element (which is also an array) use count() to obtain the number of elements and add that value to the accumulator variable.
$num_players = 0;
foreach($players as $row) {
$num_players += count($row);
}

Swap my element's order to be the first in an array

Let's say I have an array like so:
array(
[0]=>1
[1]=>3
[3]=>5
[15]=>6
);
Arbitrarily I want array[15] to be the first:
array(
[15]=>6
[0]=>1
[1]=>3
[3]=>5
);
What is the fastest and most painless way to do this?
Here are the things I've tried:
array_unshift - Unfortunately, my keys are numeric and I need to keep the order (sort of like uasort) this messes up the keys.
uasort - seems too much overhead - the reason I want to make my element the first in my array is to specifically avoid uasort! (Swapping elements on the fly instead of sorting when I need them)
Assuming you know the key of the element you want to shift, and that element could be in any position in the array (not necessarily the last element):
$shift_key = 15;
$shift = array($shift_key => $arr[$shift_key]);
$arr = $shift + $arr;
See demo
Updated - unset() not necessary. Pointed out by #FuzzyTree
You can try this using a slice and a union operator:
// get last element (preserving keys)
$last = array_slice($array, -1, 1, true);
// put it back with union operator
$array = $last + $array;
Update: as mentioned below, this answer takes the last key and puts it at the front. If you want to arbitrarily move any element to the front:
$array = array($your_desired_key => $array[$your_desired_key]) + $array;
Union operators take from the right and add to the left (so the original value gets overwritten).
If #15 is always last you can do
$last = array_pop($array); //remove from end
array_unshift($last); //push on front
To reorder the keys for sorting simply add
$array = array_values($array); //reindex array
#Edit - if we don't assume its always last then I would go with ( if we always know wwhat the key is, then most likely we will know its position or it's not a numerically indexed array but an associative one with numeric keys, as op did state "arbitrarily" so one has to assume the structure of the array is known before hand. )
I also dont see the need to reindex them as the op stated that it was to avoid sorting. So why would you then sort?
$item = $array[15];
unset($array[15]); //....etc.

Extract parts from Array keys in php and combine them

i have also got a similar question. I have an array where i need to extract parts from the keys of array and combine them. can you please suggest the best way for it.
$myarray=Array(
[0]=>'unwanted text'
[1]=>'unwanted+needed part1'
[2]=>'needed part2'
[3]=>'needed part3'
[4]=>'unwanted text'
)
how can i extract only the needed parts and combine them. Thanks a lot ahead.
Not exactly sure if this does what you want, but looping and copying to a new array should basically achieve your result (once you clarify how you decide which part of the strings are needed or unwanted)
$myarray = array(…);
$new_array = array();
$unwanted = 'some_string';
foreach($myarray as $k => $v) {
$new_value = preg_replace("/^$unwanted/", '', $v); # replace unwanted parts with empty string (removes them);
if(!empty($new_value)) { # did we just remove the entry completely? if so, don't append it to the new array
$new_array[] = $v; # or $new_array[$k] if you want to keep indices.
}
}
Assuming you want to join array entries and have a string as result, use the implode function of PHP: $string = implode(' ', $new_array);
The functions you are after, depending on what you want to do, will be a combination of the following: array_splice, array_flip, array_combine.
array_splice()
allows you to extract part of an array by key offset. It'll permanently remove the elements from the source, and return these elements in a new array
array_flip()
Turns keys into values and values into keys. If you have multiple identical values, the last one has precedence.
array_combine() takes two parameters: an array of keys, and an array of values, and returns an associative array.
You'll need to provide more info as to what you want to do, though, for my answer to be more specific.

How to get the last n items in a PHP array as another array?

How to I get an array of the last n items of another array in PHP?
$n is equal to the number of items you want off the end.
$arr = array_slice($old_arr, -$n);
You can use array_slice:
$arr = array_slice($old_arr, -$n, $n, true);
If the array indices are meaningful to you, remember that array_slice will reset and reorder the numeric array indices. You need the preserve_keys flag (4th parameter) set to true to avoid this.

Categories