min value from php array for specific key

Hi experts,

I use the following function to get the MAX value of an array for specific key

function maxValueInArray($array)
{
    $keyToSearch = 'avg_rating';
    $currentMax = NULL;
    foreach($array as $arr)
    {
        foreach($arr as $key => $value)
        {
            if ($key == $keyToSearch && ($value >= $currentMax))
            {
                $currentMax = $value;
            }
        }
    }
    return $currentMax;
}

Open in new window


Now I would like to change this function to not give me the MAX but the MIN value instead. I tried working this out but somehow I dont get it done.

thank you in advance
Oliver2000Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
I'm a bit confused.  As far as I know, 'keys' are unique in an array.  There should be only one 'key' named 'avg_rating' which means there should be only one value for it.

Also, $currentMax should probably be a defined value and not NULL.  By definition, most comparisons do not work with NULL... because it is not a value but means 'undefined'.
0
Dave BaldwinFixer of ProblemsCommented:
Use 'var_dump' to see what keys and values are in your array.
http://php.net/manual/en/function.var-dump.php
0
käµfm³d 👽Commented:
Change greater than or equal to to less than or equal to (line 9).
0
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Oliver2000Author Commented:
@Dave Baldwin: I am sorry if I did not describe it correct. I have a array with different keys and I want the MIN VALUE of a specific key. In my case the 'avg_rating'.

The current_max = NULL; seems not important. I can use either NULL or 0 or nothing the results are the same.

Var_dump looks like this:
array(7) { [7]=> object(stdClass)#34 (2) { ["created"]=> string(10) "2015-04-07" ["avg_rating"]=> string(2) "20" } [10]=> object(stdClass)#39 (2) { ["created"]=> string(10) "2015-04-10" ["avg_rating"]=> string(2) "35" } [0]=> object(stdClass)#40 (2) { ["created"]=> string(10) "2015-04-06" ["avg_rating"]=> string(2) "23" } [1]=> object(stdClass)#41 (2) { ["created"]=> string(10) "2015-04-06" ["avg_rating"]=> string(2) "23" } [3]=> object(stdClass)#42 (2) { ["created"]=> string(10) "2015-04-08" ["avg_rating"]=> string(2) "23" } [4]=> object(stdClass)#43 (2) { ["created"]=> string(10) "2015-04-09" ["avg_rating"]=> string(2) "23" } [6]=> object(stdClass)#44 (2) { ["created"]=> string(10) "2015-04-11" ["avg_rating"]=> string(2) "23" } } 35
35

@käµfm³d: It does not work like this. I tried before already ;)
0
käµfm³d 👽Commented:
You have to check for NULL as well:

if ($key == $keyToSearch && (($value <= $currentMax) || $currentMax == NULL))

Open in new window


The reason is that you haven't set the value of $currentMax yet, so the condition would always return false. Setting the value when it's null gives you something to compare to.

Of course, you'll probably want to rename "$currentMax" to something more appropriate.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
This appears to be an array of objects.  You can sort the array using usort().  One end of the sorted array will contain the max, the other will contain the min.  I'll try to give you a code sample in a moment.
http://php.net/manual/en/function.usort.php
0
Ray PaseurCommented:
See if this helps make sense of the app; please post back if you still have questions:
http://iconoun.com/demo/temp_oliver2000.php

<?php // demo/temp_oliver2000.php

/**
 * See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28658463.html
 * Ref http://php.net/manual/en/function.usort.php
 *     http://php.net/manual/en/function.current.php
 *     http://php.net/manual/en/function.end.php
 */
error_reporting(E_ALL);
echo '<pre>';


// CREATE A TEST DATA SET - AN ARRAY OF OBJECTS
$arr = array();
$obj = new stdClass; $obj->created = '2015-04-06'; $obj->avg_rating = '23'; $arr[0]  = $obj;
$obj = new stdClass; $obj->created = '2015-04-06'; $obj->avg_rating = '23'; $arr[1]  = $obj;
$obj = new stdClass; $obj->created = '2015-04-08'; $obj->avg_rating = '23'; $arr[3]  = $obj;
$obj = new stdClass; $obj->created = '2015-04-09'; $obj->avg_rating = '23'; $arr[4]  = $obj;
$obj = new stdClass; $obj->created = '2015-04-11'; $obj->avg_rating = '23'; $arr[6]  = $obj;
$obj = new stdClass; $obj->created = '2015-04-07'; $obj->avg_rating = '20'; $arr[7]  = $obj;
$obj = new stdClass; $obj->created = '2015-04-10'; $obj->avg_rating = '35'; $arr[10] = $obj;

// DOES IT LOOK RIGHT? YES
// var_dump($arr);

// PRESERVE THE ORIGINAL ARRAY - KEEP THE KEYS FOR LATER USE
$old = $arr;


// A FUNCTION TO COMPARE avg_rating
function sort_avg_rating_asc($a, $b)
{
    return ($a->avg_rating < $b->avg_rating) ? -1 : 1;
}

// A FUNCTION TO COMPARE created
function sort_created_asc($a, $b)
{
    return ($a->created < $b->created) ? -1 : 1;
}


// SORT BY created
usort($arr, 'sort_created_asc');
echo PHP_EOL . "SORTED BY created: " . PHP_EOL;
print_r($arr);

// SORT BY avg_rating
usort($arr, 'sort_avg_rating_asc');
echo PHP_EOL . "SORTED BY avg_rating: " . PHP_EOL;
print_r($arr);


// SHOW THE MIN AND MAX, SORTED BY avg_rating
echo PHP_EOL . "MIN WHEN SORTED BY avg_rating: " . PHP_EOL;
$min = current($arr);
var_dump($min);

echo PHP_EOL . "MAX WHEN SORTED BY avg_rating: " . PHP_EOL;
$max = end($arr);
var_dump($max);


// SHOW HOW TO SORT AND PRESERVE THE KEYS
$arr = $old;
foreach ($arr as $key => $obj)
{
    // INJECT THE ORIGINAL KEY INTO A PROPERTY OF THE OBJECT
    $obj->key = $key;
    $arr[$key] = $obj;
}
usort($arr, 'sort_avg_rating_asc');

// RECOVER THE ORIGINAL KEYS
$new = [];
foreach ($arr as $obj)
{
    $key = $obj->key;
    unset($obj->key); // OPTIONAL - MAY NOT BE NEEDED
    $new[$key] = $obj;
}
echo PHP_EOL . "WITH KEYS PRESERVED, SORTED BY avg_rating: " . PHP_EOL;
print_r($new);

Open in new window

0
Oliver2000Author Commented:
This was exactly what was missing for me. Easy, fast solution which does 100% the job
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.