Gorki Gorki - 6 months ago 28
PHP Question

Getting Max Value From Multi Dimensional Array Using max Function

<?php
$heading = "The Flash 3";
$arrays = array("the-flash","tv-shows","games","videos");
$playerdata = array();
foreach ($arrays as $key => $tag) {
similar_text($tag, $heading, $percent);
$playerdata = array(
'tag' => $tag,
'goals' => $percent
);
$allplayerdata[] = $playerdata;
}
print_r($allplayerdata);
?>
Result Of print_r($allplayerdata);
([0] => Array ( [tag] => the-flash [goals] => 60 )
[1] => Array ([tag] => tv-shows [goals] => 21.052631578947 )
[2] => Array ( [tag] => games [goals] => 25 )
[3] => Array ( [tag] => videos [goals] => 23.529411764706 ) )


All I Need Is Max Value And Name Of Tag i.e the-flash and goals = 60
Values Are Coming From DB.. Thnx

Answer

You can replace your foreach loop with this:

$max = $max_tag = NULL;
foreach ($arrays as $tag) {
    similar_text($tag, $heading, $percent); 
    $playerdata = array(
        'tag' => $tag,
        'goals' => $percent
    );   
    $allplayerdata[] = $playerdata;
    if (is_null($max) || $percent > $max) {
        $max = $percent;
        $max_tag = $tag;
    }
}
echo "Max = {$max}, max tag = {$max_tag}";
Comments