我试图找出整个数组中的min x和min y值,我尝试使用min和max函数但到目前为止没有成功
我在2d数组中有xy值的电路板
$xydata = array(
array('x' => 17.0, 'y' => 2.83),
array('x' => 20.83, 'y' => 65.37 ),
array('x' => 17.85,'y' => 3.57 ),
array('x' => 17.13, 'y' => 41.33 ),
array('x' => 24.27, 'y' => 53.48 ),
array('x' => 13.1, 'y' => 16.35),
array('x' => 13.1, 'y' => 66.855 )
);
我想找到董事会的角落
全局我有min x / y max x / y,我通过min()和max()函数
我想要的是最小化对抗min x
如果通过$ xydata我用min x搜索是13.1我应该得到最小16.35因为其他min x 13.1 y值是66.855更高....所以任何想法如何可以做
答案 0 :(得分:2)
示例代码:
$xydata = array(
array('x' => 17.0, 'y' => 2.83),
array('x' => 20.83, 'y' => 65.37 ),
array('x' => 17.85,'y' => 3.57 ),
array('x' => 17.13, 'y' => 41.33 ),
array('x' => 24.27, 'y' => 53.48 ),
array('x' => 13.1, 'y' => 66.855 ),
array('x' => 13.1, 'y' => 16.35),
);
$min = $xydata[0];
foreach ($xydata as $d) {
if ($d['x'] < $min['x'] || ($d['x'] == $min['x'] && $d['y'] < $min['y'])) {
$min = $d;
}
}
echo'<pre>',print_r($min),'</pre>'; // TODO
答案 1 :(得分:0)
试试这个,最好的解决方案是使用数组短路
$xydata = array(
array('x' => 17.0, 'y' => 2.83),
array('x' => 20.83, 'y' => 65.37 ),
array('x' => 17.85,'y' => 3.57 ),
array('x' => 17.13, 'y' => 41.33 ),
array('x' => 24.27, 'y' => 53.48 ),
array('x' => 13.1, 'y' => 16.35),
array('x' => 13.1, 'y' => 66.855 )
);
$count = 0;
foreach ($xydata as $type) {
$count++;
}
$count--;
function sortByOrder($a, $b) {
return $a['x'] - $b['x'];
}
usort($xydata, 'sortByOrder');
echo "min of x => ".$xydata [0]['x'];
echo "max of x => ".$xydata [$count]['x'];
function sortByOrdery($a, $b) {
return $a['y'] - $b['y'];
}
usort($xydata, 'sortByOrdery');
echo "min of y => ".$xydata [0]['y'];
echo "max of y => ".$xydata [$count]['y'];
<强> DEMO 强>
答案 2 :(得分:0)
您可以尝试以下功能:
function array_max($a) {
foreach ($a as $value) {
if (is_array($value)) {
$value = array_max($value);
}
if (!(isset($max))) {
$max = $value;
} else {
$max = $value > $max ? $value : $max;
}
}
return $max;
}
function array_min($a) {
foreach ($a as $value) {
if (is_array($value)) {
$value = array_min($value);
}
if (!(isset($min))) {
$min = $value;
} else {
$min = $value < $min ? $value : $min;
}
}
return $min;
}
它的工作对我来说很好:)。
答案 3 :(得分:0)