This question already has an answer here:
I have an array of objects $factories
and i'm looping with foreach
through that array and then through array property of the object.
$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
}
}
Why does $i['checked']=5;
not set the assoc array property of object correctly while echoing $i['checked']
retrieves the correct property value out of the object?
Here is class code:
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: yes I could probably solve this by a setter method... still i'm curious why this isn't working. Also php7
</div>