How to calculate the maximum value and minimum value of such an array
You can see at a glance that the minimum value is 0 and the maximum value is 459, but how to calculate it using php
高洛峰2017-05-18 10:48:03
1. Convert it into a one-dimensional array and use min and max to find the minimum and maximum respectively
function getMaxAndMin($items){
$newItems=[];
$cutStr=',';//要分割的字符
foreach($items as $item)
{
//保证是String并且包含','
if(is_string($item) && strpos($item,$cutStr)!==false)
{
list($t1,$t2)=explode(',',$item)
$newItems[]=$t1;
$newItems[]=$t2;
}else{
$newItems[]=$item;
}
}
return [min($newItems),max($newItems)];
}
$exampleArr=[
'0,129',
'130,249',
'250,459'
];
list($min,$max)=getMaxAndMin($exampleArr);
Add a downstairs plan, which is simpler
@jacoob_w
function getMaxAndMin($items,$operator=',')
{
$data = explode($operator, join($operator,$data));
return [min($data),max($data)];
}
伊谢尔伦2017-05-18 10:48:03
<?php
define('CLI_SCRIPT', true);
$example = array(
'0, 129',
'130, 249',
'250, 459'
);
$new_arr = [];
foreach ($example as $item) {
$new_items = explode(',', $item);
$new_arr = array_merge($new_arr, $new_items);
}
var_dump($new_arr);
sort($new_arr, SORT_NUMERIC); //排序
$min = array_shift($new_arr); //最小值
$max = array_pop($new_arr); //最大值
var_dump($min);
var_dump($max);
仅有的幸福2017-05-18 10:48:03
1. You can implement the algorithm manually, but the performance can be imagined
2. It is recommended to use PHP built-in functions: http://php.net/manual/zh/func...
世界只因有你2017-05-18 10:48:03
$arr = array(
'0,129',
'130,249',
'250,459',
);
$mix = intval($arr[0]);
$max = explode(',', end($arr))[1];
Use according to the actual situation
Because I saw that the questioner had other problems, I decided that his data structure is like this, and the size increases from top to bottom
我想大声告诉你2017-05-18 10:48:03
I adopted the answer so quickly. I personally feel that the solution I adopted is not the best one.
$data = array(
'0,129',
'130,249',
'380,22'
);
$dataArr = explode(',', join(',',$data));
echo "max:".max($dataArr)."<br/>";
echo "min:".min($dataArr);
phpcn_u15822017-05-18 10:48:03
$data = ['0,129','130,249','250,459'];
$str=implode(',',$data);
$arr=explode(',',$str);
var_dump(max($arr));
var_dump(min($arr));