I thought I have some basic PHP skills, at least enough to do the development for simple applications, but I found myself to be stuck with very basic array operation problem.
I have results of curl operation set on $results variable. For easier code, (blame me it is too primitive.), I have used the basic loop to loop through $results variable to produce the favored results for my next operation.
$data = array();
for ($i = 0; $i < count($results); $i++) {
$row = $results[$i];
$atom->objectId = $row['objectId'];
$atom->username = $row['username'];
array_push($data, $atom);
}
var_dump(json_encode($data));
Sample data:
{
[0] => { ["objectId"]: "12345", ["username"]: "user1" },
[1] => { ["objectId"]: "12567", ["username"]: "user2" },
[2] => { ["objectId"]: "12789", ["username"]: "user3" },
[3] => { ["objectId"]: "13579", ["username"]: "user4" }
}
You can simply figure out the expected output, but the real output turned out to be:
[
{ "objectId": "13579", "username": "user4" },
{ "objectId": "13579", "username": "user4" },
{ "objectId": "13579", "username": "user4" },
{ "objectId": "13579", "username": "user4" }
]
Any idea why this is giving me ridiculous result? Any help would be appreciated. Thanks in advance.
What your code is doing right now:
Every loop, it is changing the properties of one object, and appending the object's reference (pass by value, but the value is the reference.) to the
$data
array, so you have 4 spots in the$data
array pointing to only one object. Each time you loop, you change the value, the last time it is assigned is on the last value. This is why all your values are the same.What you want to do:
Create a new object every iteration with the data and point to the new object each time.
Other solution:
If you just want an array containing the values and not a reference to an object(like your output), you could try this: