Qwert Trewq
Qwert Trewq

Reputation: 77

PHP array insertions do not work as expected

I am trying to insert some items (suppose n items), which are all different from each other, to an array. Somehow, the final array consists of n items, Which all are the same item: the last inserted item.

This is my code:

$searchResults_data = [];
foreach($allowSearch as $searchResultItem) {
    $searchResultJSon->dealid = $searchResultItem['id'];
    $searchResultJSon->title = $searchResultItem['title'];
    //$from->send(json_encode($searchResultJSon)); --- DEBUGGING1 ---
    //$from->send(json_encode($searchResults_data)); --- DEBUGGING2 ---
    $searchResults_data[] =  $searchResultJSon;
}

So I tried to figure out why is that.. using DEBUGGING1,DEBUGGING2 (in the client side, I get the messages sent by $from->send() and simply alert() them).

When alerting the DEBUGGING1 messages - I do see that all the items are correct and different from each other.

When alerting the DEBUGGING2 messages - the array duplicates the last inserted item each loop. So assume I insert n items, The array in the i-th loop will be: [item-i, item-i, item-i, ... item-i] instead of [item-1, item-2, item-3,...,item-i]

Upvotes: 0

Views: 48

Answers (1)

Nick
Nick

Reputation: 147216

Your problem is that you're not creating a new object each time you go through the loop, so when you push $searchResultJSon into $searchResults_data you are pushing the same object, and the changes you make to it in the last iteration of the loop are reflected in all the values in $searchResults_data. You can work around that by creating a new object in each pass:

$searchResults_data = [];
foreach($allowSearch as $searchResultItem) {
    $searchResultJSon = new StdClass();
    $searchResultJSon->dealid = $searchResultItem['id'];
    $searchResultJSon->title = $searchResultItem['title'];
    //$from->send(json_encode($searchResultJSon)); --- DEBUGGING1 ---
    //$from->send(json_encode($searchResults_data)); --- DEBUGGING2 ---
    $searchResults_data[] =  $searchResultJSon;
}

Upvotes: 2

Related Questions