I am very new to programming, and have been banging my head against the wall trying to make this web-scraper for 2 days now. I simplified the full script (even removing all actual web-scraping), while maintaining the original dysfunction.
I guess the code is easy enough to understand for a trained eye, but for conveniance I’ll say that the script is supposed to:
- Populate an array with sub-arrays
- Set some values into each sub-array, but leaving the last sub-array value empty
- a) Get the last sub-array values with another function, 3. b) and then insert them into the original array
3.b is where the script fails. It does not enter the value (it is left empty).
I know I am using functions without parameters (the full code includes them) which might be bad, but the dysfunction remains the same without them.
<?php
$scrape = new Scraper();
class Scraper
{
protected $cars = array();
function __construct()
{
$this->getcars();
foreach ($this->cars as $item) {
$item['color'] = $this->getcolor($item); // here is the fault!
}
}
private function getcars()
{
$listofcars = array('0','1','2');
foreach ($listofcars as $item) {
$this->cars[] = array('carname' => 'humvee','color' => '');
}
}
private function getcolor()
{
return 'green';
}
}
?>
Your foreach loop isn’t passing by reference (any changes you make won’t “stick”). Change it to:
foreach ($this->cars as &$item)Edit: It also looks like
$this->getcolor($item);might be an issue. Thegetcolor()function you defined doesn’t take parameters, so you might want to make that$this->getcolor();