PHP获取并更改对象中的随机项

时间:2016-12-21 20:02:15

标签: php object random

我知道如何在数组中执行此操作,但不确定如何使用对象执行此操作。我的对象看起来像这样......

stdClass Object
(
    [Full] => 10
    [GK] => 10
    [Def] => 10
    [Mid] => 10
    [Att] => 0
    [Youth] => 0
    [Coun] => 0
    [Diet] => 10
    [Fit] => 0
    [Promo] => 10
    [Y1] => 0
    [Y2] => 9
    [Y3] => 0
    [IntScout] => 0
    [U16] => 0
    [Physio] => 4
    [Ground] => 1
)

我需要做一个循环,检查值的总和是否不大于某个值(在这种情况下为50)。如果是的话,我需要随机选择其中一个并将其减少1,直到最终总数不超过50。

到目前为止,我失败的尝试是: -

$RandomTrainer = mt_rand(0, (count($this->Trainers) -1));
if ($this->Trainers->$RandomTrainer] > 0) {
$this->Trainers->$RandomTrainer] -= 1;

显然这不起作用,因为它在对象中寻找'0'或某个数字,而不是那里。

我已经跳过了循环/总计部分,因为那是在我的最后工作。

解决方案:不完美,但有效。

$TrainerArray = get_object_vars($this->Trainers); // Cast into array.
if ($Total> 50) { // Calculated before the loop.
    $TrainerFound = 0;
    while ($TrainerFound == 0) {
        $RandomTrainer = mt_rand(0, count($TrainerArray)) - 1; // Get a random index in the array of trainers.
        reset ($TrainerArray); // Set the array to the beginning, not sure if this is needed.
        while ($RandomTrainer > 0) {
            next ($TrainerArray); // Keep advancing '$RandomTrainer' times.
            $RandomTrainer -= 1;
        }
        $propertyName = key($TrainerArray); // Get the key at this point in the array.
        $this->Trainers->$propertyName -= 1; // Reduce the value in the original object at this point by 1.

可能太啰嗦但几个小时后,我很满意它只是工作:)

1 个答案:

答案 0 :(得分:1)

您可以将变量作为数组

$vars = get_object_vars($some_std_class_object);

然后:

while(Your_function_to_sum_values($some_std_class_object) > 50)
{
    $propertyName = array_rand($vars);

    if(some_std_class_object->$propertyName > 0){
        some_std_class_object->$propertyName -= 1;
    }
}