Keep only the three highest values in array of array in php - php

I have an array of 83 arrays (an array that I have a chunk in 83). I'm trying to keep only the three highest values of each array. All the numbers in each array are included between -1 and 1. There is necessarily a 1 in each array that I don't want to count in my three highest values.
Array
(
[0] => Array
(
[1] => 0.5278533158407
[2] => 0.4080014506744
[3] => 0.5086879008467
[5] => 0.3950042642736
[6] => 1
[1] => Array
(
[1] => 1
[2] => 0.52873390443395
[3] => 0.52518076782133
[4] => 0.52983621494599
[5] => 0.54392829322042
[6] => 0.53636363636364
Etc...
I'm trying the below code but it doesn't work.
for ($i = 0; $i < sizeof($list_chunk); $i++) {
arsort($list_chunk[$i]);
}
for ($i = 0; $i < sizeof($list_chunk); $i++) {
array_slice($list_chunk[$i],1,3,true);
}
print("<pre>");
print_r($list_chunk);
print("</pre>");
Someone could help me? Thanks a lot

This solution uses a foreach loop with a reference to the subarray. The subarray is sorted in descending order of size. The first to third elements are extracted. If the first element is 1, then 3 elements are extracted from the 2 element onwards.
foreach($array as &$arr){
rsort($arr);
$start = $arr[0] == 1 ? 1 : 0;
$arr = array_slice($arr,$start,3);
}
Result:
array (
0 =>
array (
0 => 0.5278533158407,
1 => 0.5086879008467,
2 => 0.4080014506744,
),
1 =>
array (
0 => 0.54392829322042,
1 => 0.53636363636364,
2 => 0.52983621494599,
),
)
Full sample to try: https://3v4l.org/pUhic

Related

PHP - get array element between a range in multidimensional array

I have a multidimensional array. I want to get array element which value is greater than 2 and less than 17. My Array is given below:
Array
(
[4] => Array
(
[0] => 17
[1] => 15
[2] => 12
)
[5] => Array
(
[0] => 16
)
[2] => Array
(
[0] => 3
[1] => 1
)
[1] => Array
(
[0] => 2
)
)
I want output like below:
Array
(
[4] => Array
(
[0] => 17
[1] => 15
[2] => 12
)
[5] => Array
(
[0] => 16
)
[2] => Array
(
[0] => 3
[1] => 1
)
)
Please help me how can I do it easy & fast method.
You can use a nested array filter.
$result = array_filter($outer_array, function($inner_array) {
return array_filter($inner_array, function($number) {
return $number > 2 && $number < 17;
});
});
Then inner array filter will result in an empty array being passed to the outer array filter if no values are found in the specified range. The empty array will evaluate to false in the outer filter callback, eliminating that array from the result.
Demo at 3v4l.org.
Generally, we want you to show what you have tried before we'll write code for you, but this one's on the house. For future reference, include some code snippets along with your question to avoid getting downvoted.
$output = array();
for($i = 0; $i < count($arr); $i++)
{
$use = false;
for($j = 0; $j < count($arr[$i]); $j++)
{
if($arr[$i][$j] > 2 and $arr[$i][$j] < 17)
{
$use = true;
break;
}
}
if($use)
$output[] = $arr[$i];
}
return $output;

How to combine 2 arrays of different lengths while dropping part of one array?

I have 2 arrays
array 1: Array ( [0] => Merc [1] => # [2] => BM [3] => & [4] => Lotus )
array 2: Array ( [0] => 6740 [1] => 4565 [2] => 3423 )
The goal is to combine the 2 arrays and end up with:
$result = ['Merc' => 6740, 'BM' => 4565, 'Lotus' => 3423];
There is a fair amount of guidance on this already, I know, and I have read up on it but array manipulation is new to me and somehow I just cannot get my head around the logic and syntax.
Please could someone with an experienced eye tell me where I am going wrong.
I have tried:
...
//// lets echo the arrays to make sure they are correct
print_r($car);?><br><?php
print_r($part);?><br><?php
//// lets combine the 2 arrays to get an associative array
$result = [];
for($i = 0; $i < count($car); $i++){
if (($car[$i] == "&")||($car[$i] == "#")){
$i = ($i + 1);
}
foreach($car as $car) {
foreach($part as $part) {
$result[] = array(
$car => $part,
);
}
}
}
print_r($result);
The output for this is:
Array ( [0] => Array ( [Merc] => 6740 ) [1] => Array ( [BM] => 4565 ) [2] => Array ( [Lotus] => 3423 ))
The special characters to be stripped will only ever be # or &
Filter out the unwanted elements and combine them.
Code: (Demo)
$cars=['Merc','#','BM','&','Lotus'];
$parts=[6740,4565,3423];
$cars=array_diff($cars,['#','&']);
var_export(array_combine($cars,$parts));
Output:
array (
'Merc' => 6740,
'BM' => 4565,
'Lotus' => 3423,
)
p.s. You could also filter with ctype_alpha() like this: (Demo)
$cars=array_filter($cars,'ctype_alpha'); // only retain elements that are fully comprised of letters

Combine 2 arrays in PHP

I have 2 arrays that I need to combine or merge together. I am at a bit of a loss as to how to achieve this.
So the first array looks like this:
$arr1 =
Array (
[0] => Array
(
[id] => 7
[round] => 1
)
[1] => Array
(
[id] => 11
[round] => 2
)
....
And the second array looks like this:
$arr2 =
Array (
[round_1] => 21
[round_2] => 32
....
And I need the result to end up like this:
$result =
Array (
[0] => Array
(
[id] => 7
[round] => 1
[disp] => 21
)
[1] => Array
(
[id] => 11
[round] => 2
[disp] => 32
)
...... etc etc
Any ideas on where to get started for this??
Thanks
$i = 1; // Counter
$result = $arr1; // Copy $arr1 to preserve it. (if necessary)
foreach ($result as $x){
$x['disp'] = $arr2['round_' . $i];
$i ++;
}
This will iterate through Array1 setting a value for 'disp' in each sub array. This value will be pulled from Array2 and the round number would be incremented by a basic counter.
You could equally use a standard for loop for this too.
$result = $arr1; // Copy $arr1 to preserve it. (if necessary)
for($i = 0; $i < count($result); $i++){
$result[$i]['disp'] = $arr2['round_' . ($i + 1)];
}
Just make sure you do "$i + 1" when calling the value from Array2 because that doesn't seem to be 0 indexed.

Concatenate values of two arrays [duplicate]

This question already has answers here:
Cartesian Product of N arrays
(10 answers)
Closed 8 years ago.
Let's assume I have an two arrays and I want to merge every value with the other value of the array.
Array 1
array (size=2)
0 => 1
1 => 2
Array 2
array (size=2)
0 => 3
1 => 4
Wanted result array / string:
array (size=4)
0 => '1,3'
1 => '1,4'
2 => '2,3'
3 => '2,4'
I can't get my head around it. Obviously I would need to merge every one array key/value with the other ones. Is there a more elegant way then doing this in a while/foreach loop?
You need a foreach loop inside a foreach loop. (Actualy, you will have to loop through both arrays to get a concatenated product of both arrays, you don't actually need two foreach loops). You could mix: whiles, foreach, for, or php filter/intersect array functions
Example
$array1 = array(1,2);
$array2 = array(3,4);
$result = array();
foreach ($array1 as $item1){
foreach($array2 as $item2){
$result[] = $item1.','.$item2;
}
}
https://eval.in/215001
your result array Length will be array1.Length * array2.Length
2d arrays
You could also put an array inside an array like this:
$array1 = array(1,2);
$array2 = array(3,4);
$result = array();
foreach ($array1 as $item1){
foreach($array2 as $item2){
$result[] = array($item1, $item2);
}
}
//$result[0][0] = 1 -- $result[0][1] = 3
//$result[1][0] = 1 -- $result[1][1] = 4
//$result[2][0] = 2 -- $result[2][1] = 3
//$result[3][0] = 2 -- $result[3][1] = 4
We call this a 2d (2 dimensional) array, because you could grapicly display this as a grid, like displayed here above. If you would put an Array, inside an Array inside an Array, you would call this a 3 dimensional array, etc.
print_r($result); in php:
Array
(
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 1
[1] => 4
)
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 2
[1] => 4
)
)
try
$a= array ('0' => 1,'1' => 2);
$b= array ('0' => 3,'1' => 4);
for($i=0; $i<count($a); $i++) {
for($j=0; $j<count($b); $j++) {
$newarr[]= $a[$i].','.$b[$j];
}
}
print_r($newarr);//Array ( [0] => 1,3 [1] => 1,4 [2] => 2,3 [3] => 2,4 )
$a=array('1','2');
$b=array('3','4');
$res=array();
for($i=0;$i<count($a);$i++)
{
foreach($b as $bb)
{
$res[]=strval($a[$i].','.$bb);
}
}
print_r($res);//output=Array ( [0] => 1,3 [1] => 1,4 [2] => 2,3 [3] => 2,4 )

PHP: How to reorder a two dimensional array

This is how $myArray looks like:
Array
(
[0] => Array
(
[month] => 1
[atual] => 0.00
)
[1] => Array
(
[month] => 2
[atual] => 11970.99
)
[2] => Array
(
[month] => 3
[atual] => 2888.00
)
[3] => Array
(
[month] => 5
[atual] => 1500.00
)
)
I want to "fill the gaps" of the months. That is, for those months, where we have no data (4,6,8,9,10,11,12), I want the [atual] to be zero.
I tried:
$novo=array();
for ($i=1; $i <=12 ; $i++) {
$mes=$myArray[$i-1]['month'];
$atual=$myArray[$i-1]['atual'];
if(!$mes){
$novo[$i]=0;
} else{
$novo[$i]=$atual;
}
};
But this is returning:
Array
(
[1] => 0.00
[2] => 11970.99
[3] => 2888.00
[4] => 1500.00
[5] => 0
[6] => 0
[7] => 0
[8] => 0
[9] => 0
[10] => 0
[11] => 0
[12] => 0
)
[edit] now i see you have another problem, your $myArray indexes aren't matching the months.
$myArray(
array('month' => 1, 'atual' => 0.00),
array('month' => 2, 'atual' => 11970.99),
array('month' => 3, 'atual' => 2888.00),
array('month' => 5, 'atual' => 1500.00)
)
for($i = 1; $i <= 12; $i++){
$novo[$i] = 0;
}
foreach($myArray as $item){
$novo[$item['month']] = $item['atual'];
}
print_r($novo);
This worked:
$novo=array_fill(1,12,0);
for ($i=1; $i <=12 ; $i++) {
$mes=$myArray[$i-1]['month'];
$atual=$myArray[$i-1]['atual'];
$novo[$mes]=$atual;
};
With this code you get the month 1 in position 1 (not in position 0);
Also you only search in the array one time.
It's not a beautiful solution but...
$my_array = array(
array('month'=>3,'actual'=>100)
);
$results =array();
for($i=1;$i<13;$i++){
$results[$i] = 0;
}
foreach($my_array as $a){
$results[$a['month']] = $a['actual'];
}
print_r($results);
PHP has several functions that deal with sorting arrays, and here is a comparison of array's sorting functions
I didn't fully understand your question in the first response. This code should work for you. First we will create a temporary array just to hold the month and the data in an accessible format. Then we create your array :
$temp=array();
// Populate the temp array
foreach ($myArray as $row) {
if (is_array($row) && isset($row["month"])) {
$temp[$row["month"]] = $row["atual"];
}
}
// Create novo array
for ($i=0; $i <12 ; $i++) {
$novo[$i]["month"] = $i+1;
if (array_key_exists($i+1, $temp)) {
$novo[$i]['atual'] = $temp[$i+1];
} else {
$novo[$i]['atual'] = 0;
}
}

Categories