user3192649
user3192649

Reputation: 313

Iterating through PHP Array adds integer index to each item

I have a result array being returned from a search function in one of the models. Everything works fine, however, I have recently added an iteration block to redact a row of data based on an ID. Like so:

for($i=0;$i<count($searchResponse);$i++){
    if($searchResponse[$i]['id']==$user_id){
        unset($searchResponse[$i]);
    }
}   

The code works fine and removes the appropriate data correctly. However it changes the array structure from this:

 "data":[
{
"id":"1",
"name_first":"Cameron",
"name_last":"Leafe",
"industry":"IT",
"workplace":"Leafe Interactive",
"imageURL":"https:\/\/scontent-b-kul.xx.fbcdn.net\/hphotos-xfa1\/t31.0-8\/p720x720\/819309_4979120151286_1476247244_o.jpg"
},
{
"id":"8",
"name_first":"Caroline",
"name_last":"McCullough",
"industry":"IT",
"workplace":"Occupation",
"imageURL":"http:\/\/www.mothersdelight.com\/avatar\/avatar.jpg"
},
{
"id":"11",
"name_first":"Akiko",
"name_last":"McDougall",
"industry":"IT",
"workplace":"Occupation",
"imageURL":"http:\/\/www.mothersdelight.com\/avatar\/avatar.jpg"
}
]

to this:

"data":{
"1":{
"id":"3",
"name_first":"Jane",
"name_last":"Doe",
"industry":"Retail - Fashion",
"workplace":"Big-W",
"imageURL":"http:\/\/www.johndoe.pro\/img\/John_Doe.jpg"
},
"5":{
"id":"8",
"name_first":"Caroline",
"name_last":"McCullough",
"industry":"IT",
"workplace":"Occupation",
"imageURL":"http:\/\/www.mothersdelight.com\/avatar\/avatar.jpg"
},
"6":{
"id":"11",
"name_first":"Akiko",
"name_last":"McDougall",
"industry":"IT",
"workplace":"Occupation",
"imageURL":"http:\/\/www.mothersdelight.com\/avatar\/avatar.jpg"
}
}

Note the added index for each item in the second example. This small change causes all sorts of problems client side, PHP is not my normal area and I am not sure why this block is changing the structure. Usually I would work around this on the client side, however, the product is already deployed.

Any insights or suggestions on how to prevent the iteration block from causing this integer index to appear would be greatly appreciated!

Upvotes: 0

Views: 69

Answers (1)

i alarmed alien
i alarmed alien

Reputation: 9530

You can use array_splice to manipulate non-associative arrays safely:

for($i=0;$i<count($searchResponse);$i++){
    if($searchResponse[$i]['id']==$user_id){
        array_splice($searchResponse, $i, 1);
    }
}

array_splice takes the arguments

array_splice( $array, $offset, $length*, $replacementArr* )

with the second two arguments being optional. In this case, we want to remove one element from the array at index $i, so we use

array_splice( $searchResponse, $i, 1 );

Splicing can also be used to chop up arrays or replace array elements with another array, so it's a handy function to know.

Upvotes: 1

Related Questions