Reputation: 193
I'm having a problem with pushing an object into an array.
Here's my object
Products Object
(
[id] =>
[title] => Titel
[articlenumber] => Artikelnummer
[price] => Prijs
[sale_price] => Sale Prijs
[description] => Tekst
[views] => 1
[brand] => Merk
[soled] => 0
[start_date] => 2011-04-21
[end_date] => 2011-04-28
[active] => 2
[sale_text] => Sale Tekst
)
And here is my array I tryed to push everything to an array
Array
(
[0] => title, Titel
[1] => articlenumber, Artikelnummer
[2] => price, Prijs
[3] => sale_price, Sale Prijs
[4] => description, Tekst
[5] => views, 1
[6] => brand, Merk
)
As you can see my code stops when he comes to the item "soled", it does it because the value is 0. When I put this value to something else if works fine.
Here is the code im using.
$value = array();
while (next($Product)) {
$constant = key($Product);
array_push($value, $constant.", ".$Product->$constant);
echo $constant."<br>";
}
Upvotes: 0
Views: 926
Reputation: 16768
I don't know your exact needs, but its worth trying a simple cast to array.
$value = (array) $Product;
The problem with your cvrrent approach seems to be the zero evaluating to false, i think a strict compare should fix that.
$value = array();
while (next($Product) !== false) {
$constant = key($Product);
array_push($value, $constant.", ".$Product->$constant);
echo $constant."<br>";
}
The foreach
in the other answer is probably a better idea anyhow, but if you prefer the while loop for whatever reason you need to watch out for the comparison on that zero.
Upvotes: 1
Reputation:
Using a foreach loop might be a better idea, in this case:
$value = array();
foreach($obj as $key => $val)
{
array_push($value, sprintf("%s, %s", $key, $val));
}
Upvotes: 1