am trying to find out min x and min y values in whole array , i tried with min and max function but no success so far
i have xy values of board in 2d array
$xydata = array(
array('x' => 17.0, 'y' => 2.83),
array('x' => 20.83, 'y' => 65.37 ),
array('x' => 17.85,'y' => 3.57 ),
array('x' => 17.13, 'y' => 41.33 ),
array('x' => 24.27, 'y' => 53.48 ),
array('x' => 13.1, 'y' => 16.35),
array('x' => 13.1, 'y' => 66.855 )
);
i want to find corners of board
globally i have min x/y max x/y which i got through min() and max () functions
what i want is to get min y against min x
like if through $xydata i search with min x which is 13.1 i should get min y 16.35 because the other min x 13.1 y value is 66.855 is higher .... so any idea how it could be done
Sample code:
$xydata = array(
array('x' => 17.0, 'y' => 2.83),
array('x' => 20.83, 'y' => 65.37 ),
array('x' => 17.85,'y' => 3.57 ),
array('x' => 17.13, 'y' => 41.33 ),
array('x' => 24.27, 'y' => 53.48 ),
array('x' => 13.1, 'y' => 66.855 ),
array('x' => 13.1, 'y' => 16.35),
);
$min = $xydata[0];
foreach ($xydata as $d) {
if ($d['x'] < $min['x'] || ($d['x'] == $min['x'] && $d['y'] < $min['y'])) {
$min = $d;
}
}
echo'<pre>',print_r($min),'</pre>'; // TODO
Try this, best solution is use shorting of array
$xydata = array(
array('x' => 17.0, 'y' => 2.83),
array('x' => 20.83, 'y' => 65.37 ),
array('x' => 17.85,'y' => 3.57 ),
array('x' => 17.13, 'y' => 41.33 ),
array('x' => 24.27, 'y' => 53.48 ),
array('x' => 13.1, 'y' => 16.35),
array('x' => 13.1, 'y' => 66.855 )
);
$count = 0;
foreach ($xydata as $type) {
$count++;
}
$count--;
function sortByOrder($a, $b) {
return $a['x'] - $b['x'];
}
usort($xydata, 'sortByOrder');
echo "min of x => ".$xydata [0]['x'];
echo "max of x => ".$xydata [$count]['x'];
function sortByOrdery($a, $b) {
return $a['y'] - $b['y'];
}
usort($xydata, 'sortByOrdery');
echo "min of y => ".$xydata [0]['y'];
echo "max of y => ".$xydata [$count]['y'];
DEMO
You can try the below functions:
function array_max($a) {
foreach ($a as $value) {
if (is_array($value)) {
$value = array_max($value);
}
if (!(isset($max))) {
$max = $value;
} else {
$max = $value > $max ? $value : $max;
}
}
return $max;
}
function array_min($a) {
foreach ($a as $value) {
if (is_array($value)) {
$value = array_min($value);
}
if (!(isset($min))) {
$min = $value;
} else {
$min = $value < $min ? $value : $min;
}
}
return $min;
}
Its work fine for me :)
You can use array_multisort to build a function that will give you all possible pairs of min/max:
function getXY(array $xyArray, $x = 'min', $y = 'min')
{
$xFlag = $x === 'max' ? SORT_DESC : SORT_ASC;
$yFlag = $y === 'max' ? SORT_DESC : SORT_ASC;
array_multisort(
array_column($xyArray, 'x'), $xFlag,
array_column($xyArray, 'y'), $yFlag,
$xyArray
);
return array_shift($xyArray);
}
Here is working demo.
Related
I'm pretty new to PHP and i'm stuck in the following scenario. I have an array with some values and I want to get the max value in the array set.
For ex:
$array = array(
0 => array(
'1' => '123',
'2' => '120',
'3' => '30',
'4' => '150'
),
1 => array(
'1' => '123',
'2' => '122',
'3' => '30',
'4' => '158'
),
2 => array(
'1' => '123',
'2' => '129',
'3' => '300',
'4' => '150'
)
);
The value i'm expecting is 300.
I have tried the following code and i don't know how to get the maximum value from all the sub arrays.
$max = 0;
foreach( $array as $k => $v ){
//this is where i need help
}
Any kind of help would be highly appreciated.
You can flatten your array first using array_merge(...$array), then just use the max() function:
$new_array = array_merge(...$array);
echo max($new_array);
Demo
I took #Hirumina's solution and just set $max = $y if $y was > $max
$max = 0;
foreach( $array as $k => $v ) {
foreach($v as $x => $y) {
if($y > $max){
$max = $y;
}
}
}
echo $max;
$new_array = array_map(function($value){
return max($value);
}, $array);
echo max($new_array);
Here array_map function will get max value from individual $array and store in $new_array.
Then max($new_array) will give you max value.
If I have an average score of:
$average = 95.00000000
And I have an array:
$grades = array("91-100"=>"A+","80-89"=>"A","70-79"=>"B","60-69"=>"C","50-59"=>"D","0-49"=>"F");
When I try to get an average grade by doing:
$grade = $grades[$average];
I get an error:
Notice: Undefined index: 95.00000000
I think the issue comes from the the key's of the array, but is there a way to do what i'm trying to achieve?
You have to iterate over the keys, and check if your value is between them :
$grades = array("91-100"=>"A+","80-89"=>"A","70-79"=>"B","60-69"=>"C","50-59"=>"D","0-49"=>"F");
$average = 95.00000000 ;
$grade = '' ;
foreach ($grades as $val => $cur_grade) {
list($min, $max) = explode('-', $val); // split key into min and max
if ($average >= $min && $average <= $max) { // compare
$grade = $cur_grade ; // get the value
break ; // stop the loop
}
}
echo $grade ;
Will outputs :
A+
Note that if your $average is not in the range (ex. 69.9), it will match will no case. So you could use "90-100", "80-90", ...
$grades = array("90-100"=>"A+","80-90"=>"A","70-80"=>"B","60-70"=>"C","50-60"=>"D","0-50"=>"F");
$average = 69.9 ;
// ..code above..
echo $grade ; // Outputs "C"
And
$average = 70.0 ;
// ..code above..
echo $grade ; // Outputs "B"
I would suggest changing the grade array to a simpler structure, thus you would get a simpler and more predictable code
<?php
$average = 95.00000000;
$grades = array(
array(
'grade' => 'A+',
'max' => 100,
'min' => 90
),
array(
'grade' => 'A',
'max' => 89,
'min' => 80
),
array(
'grade' => 'B',
'max' => 79,
'min' => 70
),
array(
'grade' => 'C',
'max' => 69,
'min' => 60
),
array(
'grade' => 'D',
'max' => 59,
'min' => 50
),
array(
'grade' => 'F',
'max' => 49,
'min' => 0
),
);
$result = null;
$averageScore = (int) floor($average); // it's better to compare int to int instead of float to int
foreach($grades as $grade) {
if ($average < $grade['max'] && $average >= $grade['min']) {
$result = $grade['grade'];
break;
}
}
if ($result !== null) {
echo 'Your grade is: ' . $result;
} else {
echo 'Grading error, please ask your professor for details!';
}
I have an array that contains periods from 1 - 13. Sometimes the array doesn't contain data for all periods and I need to fill in the missing ones, for example:
$array = [
['period' => 7, 'y' => 20],
['period' => 8, 'y' => 20.50],
['period' => 9, 'y' => 7020],
['period' => 10, 'y' => 6520],
['period' => 11, 'y' => 65920],
['period' => 12, 'y' => 62820],
['period' => 13, 'y' => 6120],
];
For this case I need to run a php loop to fill in the missing first 6 periods with 0 y values. I've tried a variety of loops but with no joy.
Desired output:
[
['period' => 1, 'y' => 0],
['period' => 2, 'y' => 0],
['period' => 3, 'y' => 0],
['period' => 4, 'y' => 0],
['period' => 5, 'y' => 0],
['period' => 6, 'y' => 0],
['period' => 7, 'y' => 20],
['period' => 8, 'y' => 20.50],
['period' => 9, 'y' => 7020],
['period' => 10, 'y' => 6520],
['period' => 11, 'y' => 65920],
['period' => 12, 'y' => 62820],
['period' => 13, 'y' => 6120],
]
You can get good semantics with using the standard array methods. For example:
<?php
$in = [
['period' => 7, 'y' => 20],
['period' => 8, 'y' => 20.50],
['period' => 9, 'y' => 7020],
['period' => 10, 'y' => 6520],
['period' => 11, 'y' => 65920],
['period' => 12, 'y' => 62820],
['period' => 13, 'y' => 6120],
];
// collect available periods
$available = array_column($in, 'period');
// calculate missing periods
$missing = array_diff(range(1, 13), $available);
// transform missing to correct format
$addition = array_map(function ($period) { return ['period' => $period, 'y' => 0]; }, $missing);
// add missing to input
$out = array_merge($in, $addition);
// sort by period
usort($out, function ($a, $b) {
return $a['period'] <=> $b['period'];
});
// done
print_r($out);
demo: https://3v4l.org/2fDYW
start by filling the whole array you need with all period with a value of 0.
Then for each period you get in your data array, use the period id to update the value of period in the right place in the array.
Hope it helps...
You can try this
for ($i=1 $<=13, $i++) {
$exits = false;
foreach ($array as $key => $value) {
if ($value['period'] == $key) {
$exits = true;
}
}
if ($exits) {
$array[] = ['period' => $i , 'y' => 0];
}
}
This should solve your problem:
Let's say $p_array is your array that contains periods from 1 - 13.
// get all periods number that is not missed
$not_missed_periods = array();
foreach ($p_array as $p_each)
{
$not_missed_periods[] = $p_each['period'];
}
// loop for checking all valid periods i.e 1-13
for ($i=1; $i<=13; $i++)
{
// check if $i OR period is not in $not_missed_periods
if (!in_array($i, $not_missed_periods)) {
$p_array[] = array('period' => $i, 'y' => 0);
}
}
print_r($p_array);
Assuming your $array is sorted by period.
You can create a new array that copies the content or your $array and set a new content for missing periods.
$new_array = [];
for ($i = 1, $j = 0; $i <= 13; $i++) {
if ($array[$j]['period'] == $i) {
$new_array[] = $array[$j]; //copy contents
$j++;
} else {
$new_array[] = [ 'period' => $i, 'y' => 0 ]; // set new contents
}
}
Use array_column() to generate a lookup array from your input array -- effectively applying associative, numeric, first-level keys without disturbing the original row data.
Then iterate from 1 to 13. If the current iteration's integer is found in the lookup, then push the found row; otherwise push the default row containing the incremented value.
Code: (Demo)
$lookup = array_column($data, null, 'period');
$result = [];
for ($i = 1; $i <= 13; ++$i) {
$result[] = $lookup[$i] ?? ['period' => $i, 'y' => 0];
}
var_export($result);
I have an array in php
$arr = array(
array('id' => 1, 'par' => 5),
array('id' => 2, 'par' => 5),
array('id' => 3, 'par' => 5),
array('id' => 4, 'par' => 7),
array('id' => 5, 'par' => 7),
array('id' => 6, 'par' => 7),
array('id' => 7, 'par' => 9),
array('id' => 8, 'par' => 9),
...
);
Can anybody know an effective algorithm to get a first indeks of an element which has property
$arr[x]['par'] == 7. How to get the first x from the array containing 2000 elements?
Thank you
I'm not sure if using an iterator is any faster than doing it by "hand", but you could use a RecursiveArrayIterator - http://php.net/manual/en/class.recursivearrayiterator.php
$arr = array(
array('id' => 1, 'par' => 5),
array('id' => 2, 'par' => 5),
array('id' => 3, 'par' => 5),
array('id' => 4, 'par' => 7),
array('id' => 5, 'par' => 7),
array('id' => 6, 'par' => 7),
array('id' => 7, 'par' => 9),
array('id' => 8, 'par' => 9),
);
$arrayIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach ($arrayIterator as $subKey=>$subValue) {
if ($subKey == 'par' && $subValue == 9) {
$validArray = iterator_to_array($arrayIterator->getSubIterator());
$id = $validArray['id']; // This is your return array
break;
}
}
But, to be honest, doing it by hand would probably be a lot easier to understand and debug, and for 2000 records - why bother with anything more complex than:
foreach($arr as $subArray) {
if ($subArray['par'] == 9) {
$id = $subArray['id'];
break;
}
}
If you were handling more records, or had the popularity of Facebook, then start to get serious. But sometimes keeping it simple is the best way.
I used a binary search
$par = 7;
$a = 0;$i = -1;
$b = count($arr);
while(true) {
if($par == $arr[$a]['par']) { $i = $a; break; }
if($par == $arr[$m]['par']) { $i = $m; break; }
if($par == $arr[$b]['par']) { $i = $b; break; }
if($a == $m || $m == $b) break;
if($arr[$a]['par'] < $par && $par < $arr[$m]['par']) {
$b = $m; $m = floor(($a+$b)/2);
}
if($arr[$m]['par'] < $parent && $parent < $arr[$b]['par']) {
$a = $m; $m = floor(($a+$b)/2);
}
}
That example was more slow, than a $i=0;while($i < $n && $arr[$i]['par'] != $par) $i++; Can be used the array_search instead?
I have an array like this:
array (0 =>
array (
'id' => '20110209172713',
'Date' => '2011-02-09',
'Weight' => '200',
),
1 =>
array (
'id' => '20110209172747',
'Date' => '2011-02-09',
'Weight' => '180',
),
2 =>
array (
'id' => '20110209172827',
'Date' => '2011-02-09',
'Weight' => '175',
),
3 =>
array (
'id' => '20110211204433',
'Date' => '2011-02-11',
'Weight' => '195',
),
)
I need to extract minimal and maximal Weight values.
In this example
$min_value = 175
$max_value = 200
Any help on how to do this ?
Thank you !
Option 1. First you map the array to get those numbers (and not the full details):
$numbers = array_column($array, 'weight')
Then you get the min and max:
$min = min($numbers);
$max = max($numbers);
Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map:
$numbers = array_map(function($details) {
return $details['Weight'];
}, $array);
Option 3.
Option 4. If you only need a min OR max, array_reduce() might be faster:
$min = array_reduce($array, function($min, $details) {
return min($min, $details['weight']);
}, PHP_INT_MAX);
This does more min()s, but they're very fast. The PHP_INT_MAX is to start with a high, and get lower and lower. You could do the same for $max, but you'd start at 0, or -PHP_INT_MAX.
foreach ($array as $k => $v) {
$tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);
For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.
How to get a max value:
$highest_weight = max(array_column($details, 'Weight'));
How to get the min value
$lowest_weight = min(array_column($details, 'Weight'));
It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.
The problem of finding min and max can easily be solved with just two extra memory slots
$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;
foreach($input as $data) {
$weight = intval($data['Weight']);
if($weight <= $min ) {
$min = $weight ;
}
if($weight > $max ) {
$max = $weight ;
}
}
echo " min = $min and max = $max \n " ;
How about without using predefined functions like min or max ?
//find max
$arr = [4,5,6,1];
$val = $arr[0];
$n = count($arr);
for($i=0;$i<$n;$i++) {
if($val < $arr[$i]) {
$val = $arr[$i];
}
}
echo $val;
//find min
$arr = [4,5,6,1];
$val = $arr[0];
$n = count($arr);
for($i=0;$i<$n;$i++) {
if($val > $arr[$i]) {
$val = $arr[$i];
}
}
echo $val;
$num = array (0 => array ('id' => '20110209172713', 'Date' => '2011-02-09', 'Weight' => '200'),
1 => array ('id' => '20110209172747', 'Date' => '2011-02-09', 'Weight' => '180'),
2 => array ('id' => '20110209172827', 'Date' => '2011-02-09', 'Weight' => '175'),
3 => array ('id' => '20110211204433', 'Date' => '2011-02-11', 'Weight' => '195'));
foreach($num as $key => $val)
{
$weight[] = $val['Weight'];
}
echo max($weight);
echo min($weight);
<?php
$array = array (0 =>
array (
'id' => '20110209172713',
'Date' => '2011-02-09',
'Weight' => '200',
),
1 =>
array (
'id' => '20110209172747',
'Date' => '2011-02-09',
'Weight' => '180',
),
2 =>
array (
'id' => '20110209172827',
'Date' => '2011-02-09',
'Weight' => '175',
),
3 =>
array (
'id' => '20110211204433',
'Date' => '2011-02-11',
'Weight' => '195',
),
);
foreach ($array as $key => $value) {
$result[$key] = $value['Weight'];
}
$min = min($result);
$max = max($result);
echo " The array in Minnumum number :".$min."<br/>";
echo " The array in Maximum number :".$max."<br/>";
?>
$Location_Category_array = array(5,50,7,6,1,7,7,30,50,50,50,40,50,9,9,11,2,2,2,2,2,11,21,21,1,12,1,5);
asort($Location_Category_array);
$count=array_count_values($Location_Category_array);//Counts the values in the array, returns associatve array
print_r($count);
$maxsize = 0;
$maxvalue = 0;
foreach($count as $a=>$y){
echo "<br/>".$a."=".$y;
if($y>=$maxvalue){
$maxvalue = $y;
if($a>$maxsize){
$maxsize = $a;
}
}
}
echo "<br/>max = ".$maxsize;
print fast five maximum and minimum number from array without use of sorting array in php
:-
<?php
$array = explode(',',"78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73");
$t=0;
$l=count($array);
foreach($array as $v)
{
$t += $v;
}
$avg= $t/$l;
echo "average Temperature is : ".$avg." ";
echo "<br>List of seven highest temperatsures :-";
$m[0]= max($array);
for($i=1; $i <7 ; $i++)
{
$m[$i]=max(array_diff($array,$m));
}
foreach ($m as $key => $value) {
echo " ".$value;
}
echo "<br> List of seven lowest temperatures : ";
$mi[0]= min($array);
for($i=1; $i <7 ; $i++)
{
$mi[$i]=min(array_diff($array,$mi));
}
foreach ($mi as $key => $value) {
echo " ".$value;
}
?>