我必须计算两个PHP对象之间的miss项目总数,这些对象在以下类中定义:
<?php
class Module {
var $nD;
var $nC;
var $nA;
function __construct($nD, $nC, $nA) {
$this->nD = $nD;
$this->nC = $nC;
$this->nA = $nA;
}
function toString() {
return $this->nD . "-" . $this->nC . "-" . $this->nA . "<br>";
}
}
?>
有一些固定的模块,如下:
$mods = array (
'mod1' => new module ( 4, 3, 3 ),
'mod2' => new module ( 5, 3, 2 ),
'mod3' => new module ( 4, 4, 2 ),
'mod4' => new module ( 5, 4, 1 ),
'mod5' => new module ( 4, 5, 1 ),
'mod6' => new module ( 3, 5, 2 ),
'mod7' => new module ( 3, 4, 3 )
);
例如,作为输入,我输入以下模块(2,4,3),对于mod1的情况,总差异的结果将是: 4-2 = 2,3-4 = -1 - > 0(只是正值),3-3 = 0所以总计2 + 0 + 0 = 2 对于mod2将是: 5-2 = 3,3-4 = -1 - > 0(仅应加上正值),2-3 = -1 - > (只是正值)所以总计3
这是代码,用于计算差异的值:
<?php
include 'module.php';
function getmodules($id = null) {
$mods = array (
'mod1' => new module ( 4, 3, 3 ),
'mod2' => new module ( 5, 3, 2 ),
'mod3' => new module ( 4, 4, 2 ),
'mod4' => new module ( 5, 4, 1 ),
'mod5' => new module ( 4, 5, 1 ),
'mod6' => new module ( 3, 5, 2 ),
'mod7' => new module ( 3, 4, 3 )
);
if (null !== $id) {
return isset ( $mods [$id] ) ? $mods [$id] : false;
} else {
return $mods;
}
}
$module = new Module ( 2, 3, 4 );
$array = array ();
for($i = 1; $i <= 7; $i ++) {
$par = getmodules ( 'mod' . $i );
$num = 0;
if ($par->nD > $module->nD) {
$num += $par->nD - $module->nD;
}
if ($par->nC > $module->nC) {
$num += $par->nC - $module->nC;
}
if ($par->nA > $module->nA) {
$num += $par->nA - $module->nA;
}
}
?>
所以我想要的是,有一种HashMap,例如Module的键值(新模块(4,4,2))和$ num变量的值。 另外,作为下一步,我想用新月值$ num来命令HashMap。 所以输出将是这样的:
$ output = array()[对象模块mod1 =&gt; $ num of mod1,对象Module mod2,$ num of mod2];
我希望问题很清楚。如果有疑问,请问。
答案 0 :(得分:1)
写成理解
class Module {
static $matrix = array(
array ( 4, 3, 3 ),
array ( 5, 3, 2 ),
array ( 4, 4, 2 ),
array ( 5, 4, 1 ),
array ( 4, 5, 1 ),
array ( 3, 5, 2 ),
array ( 3, 4, 3 )
);
var $values = array(0,0,0);
function __construct($nD, $nC, $nA) {
$this->values = array($nD, $nC, $nA);
}
function toString() {
return implode(' - ', $this->values). "<br>";
}
function hash() {
foreach (self::$matrix as $m) {
$nm = 0;
foreach ($this->values as $key => $val) {
$n = $m[$key] - $val;
$nm += $n > 0 ? $n : 0;
}
$num[] = $nm;
}
return $num;
}
}
$module = new Module ( 2, 3, 4 );
// here you can set matrix by Module::matrix
var_dump($module->hash());
输出:
array(7) {
[0]=>
int(2)
[1]=>
int(3)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(4)
[5]=>
int(3)
[6]=>
int(2)
}