2016-01-19 10:36

# 如何从此数组中查找最小和最大值

I have this array which stores the values in the array in this format

``````Array
(
[0] => 0,20
[1] => 21,50
[2] => 201,300
[3] => 301,400
)
``````

now how will I find the smallest and the largest numeric value from it ?

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

#### 4条回答

• douying3251 5年前

I think you need minimum and maximum range.

For minimum and maximum range, first walk through array and replace

`,` by `.` so that they become numbers (comparable).

Them find out `min()` and `max()` of the resulting array.

Find out the key where the elements sit.

Now, access the elements of the original array with these keys.

``````<?php
\$org = \$result = Array(
'0,20',
'21,50',
'201,300',
'301,400',
);

\$result = array_map(function(\$el) {
return str_replace(',','.',\$el); }, \$result
);
echo '<pre>';
\$minKey = array_search(min(\$result), \$result);
\$maxKey = array_search(max(\$result), \$result);

\$min2 = \$org[\$minKey]; // Returns 0,20
\$temp = explode(',', \$min2);
\$min = \$temp[0];
echo \$min; // Prints 0

echo "<br/>";
\$max2 = \$org[\$maxKey]; // Returns 301,400
\$temp = explode(',', \$max2);
\$max = \$temp[1];
echo \$max; // Prints 400
?>
``````
点赞 评论 复制链接分享
• dp926460 5年前

You should watch out how you store your data... If I understood well, you just need to explode the array values, to mount a proper array and then use max and min functions.

Something like this:

``````\$ar = array("0,20","21,50","201,300","301,400");
foreach (\$ar as \$el) {
\$el = explode(",", \$el);
\$result[] = \$el[0];
\$result[] = \$el[1];
}

echo "min: ".min(\$result)."
";
echo "max: ".max(\$result);
``````
点赞 评论 复制链接分享
• doudou5101 5年前

Why not using min and max functions?

点赞 评论 复制链接分享
• dqm83011 5年前

Try as below :

``````\$final_array = array();
foreach(\$a as \$val)
{
\$exploded_val = explode(",",\$val);
\$final_array[] = \$exploded_val[0];
\$final_array[] = \$exploded_val[1];
}

sort(\$final_array);

\$min = \$final_array[0];
\$max = \$final_array[count(\$final_array)-1];

echo \$min.'>>'.\$max;
``````
点赞 评论 复制链接分享