I have this array:
Array ( 'jan' => 2, 'feb' => 1, 'mar' => 2, 'apr' => 1 )
..and I want to return:
Array ('jan', 'mar')
As in, find the 2 elements with the highest count and put them in an array. What is the simplest way to achieve this?
You can use max() to get the maximum value, and array_keys() to get an array containing the keys that had that value.
$max = array_keys($array, max($array));
Well, this one works when you need to get fixed number of top values.
$array = array( 'jan' => 2 'feb' => 1 'mar' => 2 'apr' => 1 );
arsort($array);
$i = 0;
$max = 2;
$newArray = Array();
foreach($array as $key => $value)
{
if ($i < $max)
{
$newArray[] = $key;
}
$i++;
}
Related
I have two arrays. They are always the same length. If the first array element value is the same then sum of the second array element value.
Example
$array1 = array(1,2,2,3);
$array2 = array(10,20,30,50);
// I can get the sum of array1 and array2 output.
$array_sum1 = array(10,50,50);
$array3 = array(4,4,4,6);
$array4 = array(10,20,30,50);
// I can get the sum of array3 and array4 output.
$array_sum2 = array(60,50);
How do I go about achieving this?
You can use array_sum with array_map like below,
$array1 = [1, 2, 2, 3];
$array2 = [10, 20, 30, 50];
$array_sum1 = [];
foreach ($array1 as $key => $value) {
$array_sum1[$value][] = $array2[$key];
}
$array_sum1 = array_map("array_sum", $array_sum1);
print_r($array_sum1);
$array3 = [4, 4, 4, 6];
$array4 = [10, 20, 30, 50];
$array_sum2 = [];
foreach ($array3 as $key => $value) {
$array_sum2[$value][] = $array4[$key];
}
$array_sum2 = array_map("array_sum", $array_sum2);
print_r($array_sum2);die;
Demo
Output:-
Array
(
[1] => 10
[2] => 50
[3] => 50
)
Array
(
[4] => 60
[6] => 50
)
It is indirect to perform two iterations of your data to group & sum.
Use the "id" values as keys in your output array. If a given "id" is encountered for the first time, then save the "val" value to the "id"; after the first encounter, add the "val" to the "id".
Code: (Demo)
$ids = [1, 2, 2, 3];
$vals = [10, 20, 30, 50];
foreach ($ids as $index => $id) {
if (!isset($result[$id])) {
$result[$id] = $vals[$index];
} else {
$result[$id] += $vals[$index];
}
}
var_export($result);
Output:
array (
1 => 10,
2 => 50,
3 => 50,
)
Here are similar (near duplicate) answers:
https://stackoverflow.com/a/53141488/2943403
https://stackoverflow.com/a/52485161/2943403
https://stackoverflow.com/a/47926978/2943403
https://stackoverflow.com/a/54421292/2943403
I have an array
$data = array(
'sam' => 40,
'james' => 40,
'sunday' => 39,
'jude' => 45
);
I want to rank the names in the array by value and return their rank order as in the array below:
$final_data = array(
'sam' => 2,
'james' => 2,
'sunday' => 4,
'jude' => 1
);
Since jude has the highest value, they get the value 1. sam and james are tied for second, so they both get 2 (3 is skipped since no one is in third place). sunday has the 4th highest score, so they get 4
You can loop the array in reverse order and count the position/rank like this:
$data = array('sam'=>40, 'james'=>40, 'sunday'=>39, 'jude'=>45);
arsort($data); // sort reverse order
$i = 0;
$prev = "";
$j = 0;
foreach($data as $key => $val){ // loop array
if($val != $prev){ // if values are the same as previous
$i++; // add one
$i += $j; // add counter of same values
$j=0;
}else{
$j++; // this is if two values after eachother are the same (sam & james)
}
$new[$key] = $i; // create new array with name as key and rank as position
$prev = $val; // overwrite previous value
}
var_dump($new);
output:
array(4) {
["jude"] => 1
["sam"] => 2
["james"] => 2
["sunday"] => 4
}
https://3v4l.org/4YvH9
With three values 40 it returns:
array(5) {
["jude"] => 1
["sam"] => 2
["james"] => 2
["tom"] => 2
["sunday"] => 5
}
I have a two dimensional haystack array like this:
[
4 => [0, 1, 2, 3, 10],
1 => [0, 1, 2, 3, 10],
2 => [0, 1, 2, 3],
3 => [0, 1, 2, 3]
]
Let's say that I have a search value of $x = 10.
How can I search in above array and get an array index which contains $x.
In my current example, subarrays with key 4 and 1 contain value of $x -- I need those 2 subarrays.
You could loop then use array_search()
$array = array(...); // Your array
$x = 10;
foreach ($array as $key => $value) {
if (array_search($x, $value)) {
echo 'Found on Index ' . $key . '</br>';
}
}
Or if you need the arrays with those index
$array = array(...); // Your array
$x = 10;
$result = array(); // initialize results
foreach ($array as $key => $value) {
if (array_search($x, $value)) {
$result[] = $array[$key]; // push to result if found
}
}
print_r($result);
You can use array_filter() to keep only the array that contains the value you want:
$array = array(
array(0, 1, 2, 3, 10),
array(0, 1, 2, 3, 10),
array(0, 1, 2, 3),
array(0, 1, 2, 3)
);
$x = 10;
$out = array_filter($array, function($arr) use($x) {
return in_array($x, $arr);
});
print_r($out);
Output:
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 10
)
[1] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 10
)
)
You can use as well in_array
$array = array(); // Your array
$x = 10;
$result = array(); // initialize results
foreach ($array as $key => $value) {
if (in_array($x, $value)) {
$result[] = $array[$key]; //
}
}
print_r($result)
You can use array_search() function to search the value in array..
Link: http://php.net/manual/en/function.array-search.php
For Exp:
$x = 10; // search value
$array = array(...); // Your array
$result = array(); // Result array
foreach ($array as $key => $value)
{
if (array_search($x, $value))
{
$result[] = $array[$key]; // push the matched data into result array..
}
}
print_r($result);
You can use array_search();
doc: http://www.php.net/manual/en/function.array-search.php
I have a multi-dimensional array and from where i want to choose 11 different words. Each word from different array index.
Here is the array link: My multi-dimensional array
array (
'w' =>
array (
0 => 'walls',
1 => 'well',
2 => 'why',
),
'e' =>
array (
0 => 'end',
),
'a' =>
array (
0 => 'advantage',
1 => 'afford',
2 => 'affronting',
3 => 'again',
4 => 'agreeable',
5 => 'ask',
6 => 'at',
),
'c' =>
array (
0 => 'children',
1 => 'civil',
2 => 'continual',
)
);
My Desire Output:
From w => well
From e => end
From a => again
and so on.
Output like: array(well, end, again, ...) as array.
Use the following code:
$f = array_keys($result); // grouping the indices, namely, the characters
$a = "";
for($c=0;$c<count($f);$c++){
$a .= $f[$c];
} // grouping the indices stored in array $f to a string, $a
$words = array();
for($c=0;$c<11;$c++){
$random = $a[rand(0,strlen($a)-1)];
$k = $result[$random];
// $k stores the array of the character index, stored in $result
$random2 = rand(0,count($k)-1);
$words[$c] = $k[$random2];
// choose a word from a given character array
$a = preg_replace("/".$random."/","",$a);
// remove the character from $a to prevent picking words which start with the same character
}
print_r($words);
I've tested and it was proved working
https://3v4l.org/qi1VP
You can achieve this usin array_rand() function :
PHP
$words = [];
$limit = 3; //Replace this with your limit, 11
$count = 0;
shuffle($array);
foreach($array as $key => $value) {
$words[] = $value[array_rand($value)];
$count++;
if ($limit == $count) {
break;
}
}
EvalIn
Check Online, and let me know.
using shuffle and array_slice you can get what you want.
A shuffle function makes your array random, and array slice slice 11 sub array from it.
Array slice takes 3 argument, first one is the array, second one is the offset from where you want to start and last one how much you need to cut.
$words = array();
shuffle($result);
$res = array_slice($result, 0, 11);
foreach($res as $key => $value){
shuffle($value);
$words[] = $value[0];
}
print_r($words);
I need to reduce the size of this array to X, so i would like to remove X random items. Here's my PHP array:
Array
(
[helping] => 3
[me] => 2
[stay] => 1
[organized!] => 1
[votre] => 4
[passion,] => 1
[action,] => 1
[et] => 2
[impact!] => 1
[being] => 4
)
I tried array_rand() but it didn't keep the keys/values.
array_rand() returns a random key (or more) of the given array, unset using that:
$randomKey = array_rand($array, 1);
unset($array[$randomKey]);
array_rand() returns an array with keys from your original array.
You would need to delete the keys from your original array using a foreach-loop.
Like this:
// Suppose you need to delete 4 items.
$keys = array_rand($array, 4);
// Loop through the generated keys
foreach ($keys as $key) {
unset($array[$key]);
}
$foo = Array(
"helping" => 3,
"me" => 2,
"stay" => 1,
"organized!" => 1,
"votre" => 4,
"passion," => 1,
"action," => 1,
"et" => 2,
"impact!" => 1,
"being" => 4
);
$max = 5; //number of elements you wish to remain
for($i=0;$i<$max;$i++){ //looping through $max iterations, removing an element at random
$rKey = array_rand($foo, 1);
unset($foo[$rKey]);
}
die(print_r($foo));
Use this,
$array = array(); // Your array
$max = 3;
$keys = array_rand($array, count($array) - $max);
// Loop through the generated keys
foreach ($keys as $key) {
unset($array[$key]);
}
If you need to remove an unknown item number, you can do :
$myArr = [
'helping' => 3,
'me' => 2,
'stay' => 1,
'organized!' => 1,
'votre' => 4,
'passion,' => 1,
'action,' => 1,
'et' => 2,
'impact!' => 1,
'being' => 4,
];
$countToRemove = random_int(1, 2); // can return 1 or 2
$keysToRemove = array_rand($myArr, $countToRemove); // returns an int or array
// create the array to loop
foreach (\is_array($keysToRemove) ? $keysToRemove : [$keysToRemove] as $key) {
unset($myArr[$key]);
}
var_dump($myArr); die();
In this case it will randomly remove 1 or 2 items from the array.