darkness darkness - 4 months ago 16
PHP Question

getting same data from storing array

public productname = array();

public function prepare_product(){
if(!empty($this->directoryfile)){

//create empty class
$imagesrc = new stdClass();

$table = $this->directoryfile;

$sql = "SELECT * FROM $table ";

$results = $this->select($sql);

while($row = $results->fetch(PDO::FETCH_ASSOC)){

//get all data from mysql.

$productname[] = $row['PRODUCT_NAME'];

}

//i think here is the problem , i get 2 array with same data.
foreach($productname as $map){
$imagesrc->name = $map;
$productImage[] = $imagesrc;
}
}
}


my intention is to create a empty class new stdClass() and store the array like,
name:product_name, but i get 2 array with same data.

it suppose like this name:product_name1, name:product_name2; but i got return like this name:product_name2, name:product_name2;

how to i get the things i want ? if i store the data with using the stdclass() $imagesrc , i get data i want without the name title.

$productImage[] = $map;

Answer

You are replacing the attribute 'name' every iteration and referencing the same object.

Jeff gave the answer.

If you absolutely need the second iteration for future purposes

Do:

foreach($productname as $map){
    $imagesrc = new stdClass();
    $imagesrc->name = $map;
    $productImage[] = $imagesrc;
}

Or:

foreach($productname as $map){
    $imagesrc->name = $map;
    $productImage[] = clone($imagesrc);
}
Comments