I have 2 arrays : “Array-List” and “Array-Criteria” :
Array-List
(
[1] => APPLE
[2] => BANANA
[3] => ORANGE
[4] => LEMON
)
Array-Criteria
(
[0] => 1
[1] => 3
)
Is there a quick way (my Array-List can consist of thousands of entries) to select the values from Array-List based on Array-Criteria without looping through Array-List in PHP?
Use array_intersect_key and array_flip functions to get data as:
$arr1 = Array-List
(
[1] => APPLE
[2] => BANANA
[3] => ORANGE
[4] => LEMON
)
$arr2 = Array-Criteria
(
[0] => 1
[1] => 3
)
var_dump(array_intersect_key($arr1, array_flip($arr2)));
If you loop over the criteria, you can build a list of the macthing items...
$selected = [];
foreach ( $arrayCriteria as $element ) {
$selected[] = $arrayList[$element];
}
Then $selected will be a list of the items your after.
Also in a quick test, it's about twice as fast as using the array_ methods.
Related
I would like to sum up several arrays. I have a script that dynamically creates arrays without name. Below is an example. In my script i have a 90+ arrays. I want to sum up all it. All keys in that arrays be user id, so i only want sum values of keys. How to do it? Regards
Array
(
[1] => 1
[2] => 1
[3] => 1
)
Array
(
[1] => 1
[2] => 1
)
Array
(
[1] => 1
)
I want to get only one array result like:
Array
(
[1] => 3
[2] => 2
[3] => 1
)
Add all your arrays into one array.
$all_arrays[] =Array
(
[1] => 1 ,
[2] => 1,
[3] => 1
);
$all_arrays[] = Array
(
[1] => 1,
[2] => 1
) ;
$all_arrays[] = Array
(
[1] => 1
);
$results = [];
foreach($all_arrays as $arr){
foreach($arr as $user_id=>$value){
if(in_array($user_id,$results)){
$results[$user_id] = $results[$user_id] + $value;
}else{
$results[$user_id] = $value;
}
}
}
You would need to specify all arrays in the array_merge:
$result = array_count_values(array_keys(array_merge($array1, $array2, $array3)));
If you can get the arrays dynamically added to another $main_array like:
Array
(
[0] => Array
(
[1] => 1
[2] => 1
[3] => 1
)
[1] => Array
(
[1] => 1
[2] => 1
)
[2] => Array
(
[1] => 1
)
)
Then it would be much easier:
$result = array_count_values(array_keys(array_merge(...$main_array)));
I have a PHP array that looks like this
Array
(
[0] => Array
(
[events] => Array
(
[0] => Array
(
[label] => apple
[id] => 3
)
[1] => Array
(
[label] => onion
[id] => 3
)
[2] => Array
(
[label] => pear
[id] => 2
)
[3] => Array
(
[label] => orange
[id] => 1
)
[4] => Array
(
[label] => grape
[id] => 41
)
)
)
)
I am trying to get a total count of unique IDs, so in the example above I would want to get a count of 4
Do I need to loop through the array or is there a function that can do it more efficiently? Currently it is a small data set but it could grow fairly large.
You can use array_column to get all the IDs, and array_unique to remove the duplicates, then count that.
count(array_unique(array_column($array[0]['events'][0], 'id')))
One way or another you'll have to loop through it. I think most efficiently would be
function getUnique($arr){
$val = array();
foreach($arr[0]["events"] as $v){
$val[$v["id"]] = true;
}
return count($val);
}
I'm having some difficulties figuring out how to return the best unique match, while assigning as many as possible.
Scenario: Each kid has a list of favorite fruits with a personal score. We only have ONE of each fruit, so we want to give it to the kid with the highest preference. One can be left without fruit if someone has a higher score, but we still want to give out as many fruits as possible.
The expected result would be:
0 = [1] Apple
1 = [0] Mango
2 = [0] Banana
3 = null
This is my input array:
Array
(
[0] => Array
(
[0] => Array
(
[name] => Banana
[score] => 80.2
)
[1] => Array
(
[name] => Apple
[score] => 40
)
)
[1] => Array
(
[0] => Array
(
[name] => Mango
[score] => 70
)
[1] => Array
(
[name] => Banana
[score] => 40
)
)
[2] => Array
(
[0] => Array
(
[name] => Banana
[score] => 90
)
[1] => Array
(
[name] => Orange
[score] => 20
)
)
[3] => Array
(
[0] => Array
(
[name] => Mango
[score] => 60
)
)
)
My approach first flattens your input into a simple 2D array allowing all rows to be sorted by score while preserving the fruit and childid data. After sorting, all rows are iterated (versus doing iterated full-array searches) and only stores the most preferred fruit, if available, for each child as requested.
OP's Input:
$input=[
[['name'=>'Banana','score'=>80.2],['name'=>'Apple','score'=>40]],
[['name'=>'Mango','score'=>70],['name'=>'Banana','score'=>40]],
[['name'=>'Banana','score'=>90],['name'=>'Orange','score'=>20]],
[['name'=>'Mango','score'=>60]]
];
Method:
$result=array_fill_keys(array_keys($input),null); // list all child ids and default to null
// flatten input array for simple sorting and iteration
foreach($input as $i=>$subarrays){
foreach($subarrays as $a){
$restructured[]=['score'=>$a['score'],'fruit'=>$a['name'],'childid'=>$i];
}
}
rsort($restructured); // will sort the array by score DESC
foreach($restructured as $a){
if(is_null($result[$a['childid']]) && !in_array($a['fruit'],$result)){
// only "fruitless" children wanting what is available
$result[$a['childid']]=$a['fruit'];
}
}
var_export($result);
Output:
array (
0 => 'Apple',
1 => 'Mango',
2 => 'Banana',
3 => NULL,
)
I have an array of $Percentages1 that I have ordered in descending order using arsort() and then I have taken an array containing the new key order using array_keys() called $keyorder
My question is how do I now rearrange another array $Percentages2 into the same key order as $Percentages1?
Any help will be greatly appreciated, thanks very much!
Edit - Code as requested:
//$Percentages1 before sort for example =
// Array ( [0] => 5.10 [1] => 1.52 [2] => 8.42 [3] => 1.11 [4] => 1.35 )
arsort($Percentages1);
//$Percentages1 after sort =
// Array ( [2] => 8.42 [0] => 5.10 [1] => 1.52 [4] => 1.35 [3] => 1.11 )
$keyorder = array();
//So $keyorder is =
// Array ( [0] => 2 [1] => 0 [2] => 1 [3] => 4 [4] => 3 )
$keyorder = array_keys($Percentages1);
//Now I want to do something here to rearrange a $Percentages2 array
//in the same index order as $keyorder.
//For example from this
// Array ( [0] => 2.50 [1] => 3.52 [2] => 9.42 [3] => 9.81 [4] => 0.35 )
//To...
// Array ( [2] => 9.42 [0] => 2.50 [1] => 3.52 [4] => 0.35 [3] => 9.81 )
If you are not adverse to creating another array variable, the simplest course here is just to loop over $keyorder and append the elements at the corresponding key from $Percentages2 onto a new array;.
// Sorted as you already have it...
$keyorder = array_keys($Percentages1);
// Final array
$output = array();
foreach ($keyorder as $key) {
$output[$key] = $Percentages2[$key];
}
// Don't need the source anymore
unset($Percentages2);
Their key order as appended onto $output will be retained in the final result.
Given your input arrays, this produces
print_r($output);
Array
(
[2] => 9.42
[0] => 2.5
[1] => 3.52
[4] => 0.35
[3] => 9.81
)
You actually don't need to use array_keys(). Following the call to arsort(), you can foreach over the sorted $Percentages1 and sort to $output by key:
// Skip array_keys, and read the sorted array directly
arsort($Percentages1);
foreach ($Percentages1 as $key => $value) {
// Same as before inside the loop
$output[$key] = $Percentages2[$key];
}
So I have an array such as this one:
Array
(
[-1] => Array
(
[3] => 3
[1] => 1
[6] => 6
[7] => 7
[5] => 5
)
)
It also contains some other keys that should not be modified.
I'd like to the numbers which are in a second array to come first (in the order of that second array), and then will be the numbers that don't exist in the second array, if any.
So for that matter, the second array would be:
Array
(
[0] => 6
[1] => 5
[2] => 3
)
And the final array should be as follows (please remember, there are some more keys inside of that array that should stay as they are):
Array
(
[-1] => Array
(
[6] => 6
[5] => 5
[3] => 3
[1] => 1
[7] => 7
)
)
Any ideas how that can be done?
Thanks!
It's not and shouldn't be termed as sorting but may be this code snippet may help you do what you want to:
$a1 = Array ( [-1] => Array ( [3] => 3 [1] => 1 [6] => 6 [7] => 7 [5] => 5 ) );
$a2 = Array ( [0] => 6 [1] => 5 [2] => 3 );
$sorted = getSortedArray($a1[-1] , $array2);
function getSortedArray($array1 , $array2){
$temp = Array();
$count = 0;
$totalKeys = sizeof($array2);
for($i=0;$i<sizeof($array2);$i++){
$temp[i] = $array1[$array2[i]];
unset($array1[$array2[i]]);
}
while($count!=sizeof($array1))
$temp[$totalKeys++] = $array1[$count++];
return $temp;
}
I believe the function you're looking for is called array_multisort().
array_multisort() can be used to sort
several arrays at once, or a
multi-dimensional array by one or more
dimensions.