通过PHP数组迭代为每个项添加整数索引

时间:2014-09-09 05:59:40

标签: php arrays

我从其中一个模型中的搜索功能返回结果数组。一切正常,但是,我最近添加了一个迭代块来根据ID编辑一行数据。像这样:

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

代码工作正常并正确删除适当的数据。但是它会改变数组结构:

 "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"
}
]

到此:

"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"
}
}

请注意第二个示例中每个项目的添加索引。这个小小的改变导致了客户端的各种问题,PHP不是我的正常区域,我不确定为什么这个块正在改变结构。通常我会在客户端解决这个问题,但是,产品已经部署完毕。

有关如何防止迭代块导致此整数索引出现的任何见解或建议将非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以使用array_splice安全地操作非关联数组:

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

array_splice接受参数

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

,后两个参数是可选的。在这种情况下,我们想要从索引$ i的数组中删除一个元素,因此我们使用

array_splice( $searchResponse, $i, 1 );

拼接也可用于切割数组或用另一个数组替换数组元素,因此这是一个方便的功能。