【问题标题】:php foreach fails to set array property of the object [duplicate]php foreach无法设置对象的数组属性[重复]
【发布时间】:2017-11-21 21:39:00
【问题描述】:

我有一个对象数组 $factories,我正在循环使用 foreach 通过该数组,然后通过对象的数组属性。

$f->inputResources[0]['checked']=2; // this sets the array correctly
foreach($factories as $f){
    foreach($f->inputResources as $i){
        echo $i['resource']." ".$i['amount']." ".$i['checked']."<br>"; // these values are correctly retrieved from the object
        $i['checked']=5; // but this doesn't set the object's array although it sets the $i['checked'] that is echoed down correctly

        echo $i['resource']." ".$i['amount']." ".$i['checked']."<br>";//looks like it was set correctly

        echo print_r($f-> inputResources); //here we figure out it wasn't set correctly to 5 and it's still the old value
    }
}

为什么$i['checked']=5; 没有正确设置对象的关联数组属性,而回显$i['checked'] 从对象中检索到正确的属性值?

这是课程代码:

class factory
{
var $id;
var $name;
var $player; //the owner
var $planet;
var $type;
var $govOwned; //0 player owned 1 government owned
var $output; //0 factory storage 1 market
var $price; //price of auto market ouput
var $resource;//resource which factory is producing

var $workers;
var $wage;
var $money;
var $starveIndex;

var $inputResources;
var $reservedResources;

var $storage;

public function __construct($data)
{
    $this->id = $data['id'];
    $this->name = $data['name'];
    $this->player = $data['player_id'];
    $this->planet = $data['planet_id'];
    $this->type = $data['factory_type'];
    $this->govOwned = $data['gov_owned'];
    $this->output = $data['output_where'];
    $this->price = $data['price'];
    $this->resource = $data['resource_id'];
    $this->workers = $data['workers'];
    $this->wage = $data['worker_wage'];
    $this->starveIndex = $data['workers_starve'];

    $this->inputResources[] = array('resource' => $data['resource_needed'], 'amount' => $data['amount'], 'checked' => 0);

    // etc.
}

public function addInputResource($resource, $amount)
{
    $this->inputResources[] = array('resource' => $resource, 'amount' => $amount, 'checked' => 0);
}

public function addStorage($resource, $amount)
{
    $this->storage[] = array('resource' => $resource, 'amount' => $amount);
}

}

PS:是的,我可能可以通过 setter 方法解决这个问题......我仍然很好奇为什么这不起作用。还有php7

【问题讨论】:

    标签: php arrays object foreach


    【解决方案1】:

    来自 PHP foreach 手册:http://php.net/manual/en/control-structures.foreach.php

    为了能够直接修改循环中的数组元素,在 $value 之前加上 &。在这种情况下,值将通过引用分配。

    <?php
        $arr = array(1, 2, 3, 4);
        foreach ($arr as &$value) {
           $value = $value * 2;
        }
        // $arr is now array(2, 4, 6, 8)
        unset($value); // break the reference with the last element
    ?>
    

    【讨论】:

    • 这适用于我的代码。这是一种不好的做法和/或这会使性能变差吗?
    • 我不会说这是不好的做法。如果您有它的用例,请使用它。
    猜你喜欢
    • 1970-01-01
    • 2015-04-27
    • 2019-07-20
    • 1970-01-01
    • 2015-03-14
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多