/ /クラス内の配列を循環する-php、arrays、class、next

クラスphp、配列、クラス、次の配列を循環する

ここで、私のクラスの1つから本当に奇妙な出力を取得しています。

class group
{
public $myArray = array(); // an array of fraction objects

// find the smallest fraction
private function smallest()
{
$result = array("num"=>NULL, "den"=>NULL); // this is what is returned
// initialize temp variables
$fractionObj = reset($this->myArray); // pointer to first element of array
while($fractionObj->dropped == 1)
{
$fractionObj = next($this->myArray); // move the pointer ahead until finding a fraction that is not already dropped. RESULTS IN "Notice: Trying to get property of non-object" ERROR on this line
}
$decimal = ($fractionObj->numerator/$fractionObj->denominator); // initialized to the first fraction value that is not dropped
$result["num"] = $fractionObj->numerator;
$result["den"] = $fractionObj->denominator;
$lowest = $fractionObj;
foreach($myArray as $a)
{
if($a->dropped == 0 && $a->numerator/$a->denominator < $decimal)
{
$decimal = $a->numerator/$a->denominator;
$result["num"] = $a->numerator;
$result["den"] = $a->denominator;
$lowest->dropped = true; // mark this value as dropped so it is ignored for the next call to smallest()
}
}
return $result;
}
}

class fraction
{
public $numerator;
public $denominator;
public $dropped = false;
}

ここにあるのは、以下を含むグループクラスです分数クラスオブジェクトの配列。新しいグループオブジェクトが作成されると、配列に配置される分数で構築され、すべて正常に機能します。

私は最小のX番号を見つけようとしています分数(10進値に基づく)および最小値を「ドロップ」としてマークします。これは、それらがまだ配列に残るが、それらを無視することを意味します。それは、$ dropped変数が分数クラスで示すことです。私はこれを、smallest()関数を呼び出すループで行います

問題は、私が通知を受け取っているということです非オブジェクトのプロパティ、つまり$ fractionObj-> droppedを取得しようとしています。ただし、var_dump($ fractionObj)を使用すると、オブジェクトであることがわかります。配列ポインタをこれが問題だと思うので、next()を使用せずに配列内の次のオブジェクト。

回答:

回答№1は0

私は次の解決策で解決することができました。 「もっと良い方法があるはずです。next()で繰り返し処理できると本当に便利だっただろうが、オブジェクトでは直観的に機能しないと思います。」

class group
{
public $myArray = array(); // an array of fraction objects

// find the smallest fraction
private function smallest()
{
$result = array("num"=>NULL, "den"=>NULL); // this is what is returned
foreach($this->myArray as $a)
{
if($a->dropped == false)
{
if(!isset($val))
{
$val = $a->percent();
$lowest = $a;
$result["num"] = $a->nominator;
$result["den"] = $a->denominator;
}else{
if($a->percent() < $val)
{
$val = $a->percent();
$lowest = $a;
$result["num"] = $a->nominator;
$result["den"] = $a->denominator;
}
}
}
}
$lowest->drop();
return $result;
}
}

class fraction
{
public $numerator;
public $denominator;
public $dropped = false;

public function percent()
{
return $this->numerator/$this->denominator;
}

public function drop()
{
$this->dropped = true;
}
}