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;
}
?>
Related
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!';
}
am trying to get output of following array in one format. its not getting
<?php
$distance_covered = array( '1_JAN_2017' => array('DRIVER_1' => array(2, 5, 3),'DRIVER_2' => array(3, 2, 6, 9)),
'2_JAN_2017' => array('DRIVER_1' => array(3, 9), 'DRIVER_3' => array(1, 4, 8)),
'3_JAN_2017' => array('DRIVER_4' => array(9), 'DRIVER_1' => array(2, 7, 5, 2)),
'4_JAN_2017' => array('DRIVER_1' => array(5, 3, 3, 2), 'DRIVER_4' => array(4, 9, 8, 5)),
'5_JAN_2017' => array('DRIVER_2' => array(8, 5), 'DRIVER_5' => array(3, 9, 7)),
'6_JAN_2017' => array('DRIVER_5' => array(2, 1, 7, 5), 'DRIVER_4' => array(1, 9, 6)),
'7_JAN_2017' => array('DRIVER_4' => array(5, 2, 9), 'DRIVER_3' => array(4, 1, 6)), );
The above is my array
i want output in the following format
Output: Array ( [DRIVER_1] => 51, [DRIVER_2] => 33, [DRIVER_3] => 24, [DRIVER_4] => 67, [DRIVER_5] => 34 )
this is the sum of distance travelled by each driver in all trips
i tried code like this,anybody knows please help
$res = array();
foreach($distance_covered as $value) {
foreach($value as $key => $number) {
(!isset($res[$key])) ?
$res[$key] = $number :
$res[$key] += $number;
}
}
print_r($res);
?>
This one works for me
$res = array();
foreach($distance_covered as $value)//the array which you have given us
{
foreach($value as $key => $number) //loop over array of date
{
if(!isset($res[$key]))//check if the key exist in over defined array if no then run this
{
$res[$key] = array_sum($number);// Sum all distances of that driver
continue;//set the key and continue the foreach...
}
$res[$key] += array_sum($number);// Sum all distances of that driver
}
}
print_r($res);
die;
And the Output is
Array
(
[DRIVER_1] => 51
[DRIVER_2] => 33
[DRIVER_3] => 24
[DRIVER_4] => 67
[DRIVER_5] => 34
)
This should work:
$res = array();
foreach($distance_covered as $value) {
foreach($value as $key => $number) {
foreach ($number as $n) {
if (isset($res[$key])) {
$res[$key] += $n;
} else {
$res[$key] = $n;
}
}
}
}
print_r($res);
Just traverse through array of arrays.
$distance_covered = array(
'1_JAN_2017' => array('DRIVER_1' => array(2, 5, 3),'DRIVER_2' => array(3, 2, 6, 9)),
'2_JAN_2017' => array('DRIVER_1' => array(3, 9), 'DRIVER_3' => array(1, 4, 8)),
'3_JAN_2017' => array('DRIVER_4' => array(9), 'DRIVER_1' => array(2, 7, 5, 2)),
'4_JAN_2017' => array('DRIVER_1' => array(5, 3, 3, 2), 'DRIVER_4' => array(4, 9, 8, 5)),
'5_JAN_2017' => array('DRIVER_2' => array(8, 5), 'DRIVER_5' => array(3, 9, 7)),
'6_JAN_2017' => array('DRIVER_5' => array(2, 1, 7, 5), 'DRIVER_4' => array(1, 9, 6)),
'7_JAN_2017' => array('DRIVER_4' => array(5, 2, 9), 'DRIVER_3' => array(4, 1, 6)), );
// Counting.
$merged = [];
foreach ($distance_covered as $day => $stats) {
foreach ($stats as $driver => $distances) {
if (!isset($merged[$driver])) {
$merged[$driver] = 0;
}
$merged[$driver] += array_sum($distances);
}
}
// Display.
echo "<pre>";
print_r($merged);
echo "</pre>";
You are close, but...
$res = array ();
foreach ( $distance_covered as $value ) {
foreach ( $value as $key=> $driver ) {
if ( isset($res[$key]) == false ){
$res[$key]=0;
}
$res[$key] += array_sum($driver);
}
}
print_r($res);
The first foreach simply splits the data down to the days.
The second one returns elements like $key = 'DRIVER_1' and $driver = array(3, 9).
If this is the first time you've encountered this driver, then you need to ensure that the element in $res exists, so set it to 0.
Once you know there is an element there, you can add in the sum of the values ( 3 & 9 in this case ) using the += array_sum($driver) bit. The += is simply adding to rather than having to say a=a+b, you can say a+=b.
[sarcastic voice] I can't believe everybody overlooked this convoluted function-based one-liner...
Code: (Demo)
var_export(array_map('array_sum', array_merge_recursive(...array_values($distance_covered))));
Output:
array (
'DRIVER_1' => 51,
'DRIVER_2' => 33,
'DRIVER_3' => 24,
'DRIVER_4' => 67,
'DRIVER_5' => 34,
)
*this is virtually guaranteed to process slower than any other posted answer.
Remove the first level associative keys (date strings) with array_values()
Unpack the array of arrays with the "splat operator" (...) and feed to array_merge_recursive() to group values
Sum the subarray values by calling array_sum() on each subarray with array_map()
(This is merely an exercise of thinking outside the box.)
Beyond that no one suggested using a null coalescing operator, so I'll post what that can look like:
$driver_totals = [];
foreach ($distance_covered as $daily_log) {
foreach ($daily_log as $driver => $distances) {
$driver_totals[$driver] = ($driver_totals[$driver] ?? 0) + array_sum($distances);
}
}
var_export($driver_totals);
And if you have a special scenario where you only need to know the distance for a single specific driver, you can call upon array_column() like this:
$target_driver = 'DRIVER_4';
$total_distance = 0;
foreach (array_column($distance_covered, $target_driver) as $distances) {
$total_distance += array_sum($distances);
}
echo "{$target_driver} drove for a distance of {$total_distance}";
*Notice that the order of the drivers within each date array is inconsequential because array_column() is smart enough to find the desired distance subarray.
Finally, if you declare a whitelist array of all possible drivers, you can:
control the order of the drivers in the output
avoid the iterated isset() conditions
ensure that drivers without any distance records are included in the output
Code:
$roster = ['DRIVER_6', 'DRIVER_5', 'DRIVER_4', 'DRIVER_3', 'DRIVER_2', 'DRIVER_1'];
$driver_totals = array_fill_keys($roster, 0);
foreach ($distance_covered as $daily_log) {
foreach ($daily_log as $driver => $distances) {
$driver_totals[$driver] += array_sum($distances);
}
}
var_export($driver_totals);
I have an array like the following:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1005, "id_user" => 5));
So it means 5 => 1004, 1005 and 4 => 1000, 1001, 1003 and 3 => 1002.
First, how do I get this structure? (possible with commas)
My algorithm for this solution would be something like (here's what I'm asking you guys..how to accomplish this):
$arr = array();
for($i = 0; $i <= count($content) - 1; $i++){
if exists key ($content[$i]['id_user']) IN $arr then
$arr = add_to_existing_key "," . $content[$i]['id_post']
} other wise {
$arr = add_new_key PLUS value $content[$i]['id_user'] <=> $content[$i]['id_post']
}
}
I need the commas so I could parse the info later.
Basically, the objective of this is to do a loop with $arr variable. Imagining that the array would have, finally, something like:
("id_user" => 5, "ids" => '1004,1005'),
("id_user" => 4, "ids" => '1000,1001,1003'),
("id_user" => 3, "ids" => '1002')
for($i = 0; $i <= count($arr) - 1; $i++){
$ids = explode(",", $arr[$i]['ids']);
$info = array();
for($y = 0; $y <= count($ids) - 1; $y++){
$query->("SELECT * FROM table WHERE id = $ids[$y]");
$info[] = array($name, $description);
}
$email->sendEmail($info); // id = 5 => info OF 1004, 1005
$info = array(); // clear array
// loop
// id = 4 => info OF 1000, 1001, 1003
// loop etc
}
Try this:
$arr = array();
// Loop through each content
foreach ($content as $post)
{
$arr[$post['id_user']][] = $post['id_post'];
}
This way, the result would be
$arr = array(
'5'=> array('1004', '1005'),
'4'=> array('1000', '1001', '1003'),
'3'=> array('1002')
);
Then you won't need to use "explode" just to split those comma-separated IDs
Also
I think you might be better off sticking with arrays instead of joining on commas and then exploding later:
foreach($content as $values) {
if(!isset($result[$values['id_user']])) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
print_r($result);
May be this variant will be exactly what you need:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1005, "id_user" => 5));
// Make preparation array
foreach ( $content as $values ) {
if ( !isset($result[$values['id_user']]) ) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
// Sort inner arrays
foreach ( $result as $key => $valueArray ) {
asort($result[$key]);
}
// Implode arrays to strings
array_walk($result, function(&$array, $key) {
$array = implode(',', $array);
});
// Final array
$result1 = array();
foreach ( $result as $userID => $idsString ) {
$result1[] = array("id_user" => $userID, "id_post" => $idsString);
}
print_r($result1);
I want to compare keys from one array against values from another array, and when a match is made to store the value from the first array (whose key matched the value in the second one).
With my code, it always echoes out 4. How can I modify it so that it echoes out 1 2 3 4?
The code:
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
while ($el = current($second)) {
$d .= ','.key($second);
next($second);
}
$d = ltrim($d, ',');
$d = explode(',', $d);
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
}
}
echo $t.'<br>';
}
To be honsest, if you wouldn't explain your goal, I wouldn't even understand what you're trying to do by your code. Try like this:
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$intersect = array_intersect($first, array_keys($second));
foreach($intersect as $key)
echo $second[$key];
?>
You should move/add add an echo statement into the block where you assign the value of $t, maybe this way:
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
echo $t.' ';
}
}
echo '<br>';
}
you can flip the keys in second array, and then take the intersection of the 2. something along these lines
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$flipped = array_flip($second);
print implode(' ',array_keys(array_intersect($flipped, $first)));
?>
I trying to get the minimum values from the any column contains "xx" in the column name.
Below is my code:
<?php
$array = array(
array(
'id' => 1,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
foreach($array as $item)
{
$lowestKey = '';
foreach($item as $key => $value)
{
if(strpos($key, 'xx') === 0)
{
if($lowestKey == '')
{
$lowestKey = $key;
}
else
{
if($value < $item[$lowestKey])
{
$lowestKey = $key;
}
}
}
}
echo 'lowest for id ' . $item['id'] . ': ' . $item[$lowestKey] . "\n";
}
?>
You have a function already for it:
http://php.net/manual/en/function.min.php
echo min(2, 3, 1, 6, 7); // 1
echo min(array(2, 4, 5)); // 2
echo min(0, 'hello'); // 0
echo min('hello', 0); // hello
echo min('hello', -1); // -1
Combine it with array_values if this fits better your needs.
function _getNumber($array) {
return $array['id'];
}
$numbers = array_map('_getNumber', $array);
OR
$numbers = array_map(function($array) {
return $array['id'];
}, $array);
echo $min = min($numbers);
echo $max = max($numbers);
function find_lowest($array){
$new_array = array();
foreach($array as $key => $val ){
if(is_array($val)){
$new_array[$key] = find_lowest($val);
}else{
$new_array[$key] = $val ;
}
}
return min($new_array);
}
$array = array( array( 'id' => 1,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
echo find_lowest($array);
Instead of looping again inside just use the min() function.
$lowest_keys = array();
foreach($array as $item)
{
unset( $item[ 'id' ] );
$lowest_keys[] = min( $item );
}
Iterate each row/subarray with a foreach() loop or array_walk().
Extract and display the id (first element) value with array_shift().
Call min() on the remaining values in the respective subarray to determine the lowest value.
No conditional expressions. No unnecessary variables. Clean, concise, and effective.
Code: (Demo)
$array = [
['id' => 1, '10xx' => 14, '11xx' => 32, '12xx' => 4],
['id' => 2, '10xx' => 13, '11xx' => 36, '12xx' => 41]
];
array_walk($array, function($row) {
echo array_shift($row) , " : " , min($row) , "\n";
});
Output:
1 : 4
2 : 13
$array = array(
array(
'id' => 14,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
$lowestKey = '';
foreach($array as $arra){
foreach ($arra as $key=>$value){
if ($key == 'id'){
if(($value < $lowestKey )||( $lowestKey== '')){
$lowestKey = $value;
}
}
}
}
echo $lowestKey;