开发者

How to delete values in two dimensional array (PHP)?

开发者 https://www.devze.com 2023-02-20 14:21 出处:网络
I have an array which looks like $cclArray[0][\'url\']=\'test.html\'; $cclArray[0][\'entity_id\']=9; $cclArray[1][\'url\']=\'test1.html\';

I have an array which looks like

        $cclArray[0]['url']='test.html';
        $cclArray[0]['entity_id']=9;
        $cclArray[1]['url']='test1.html';
        $cclArray[1]['entity_id']=10;
        $cclArray[2]['url']='test2.html';
        $cclArray[2]['entity_id']=11;

if i would like to remove a specific array, for example if i want to delete the array element with 'url'='test1.html'开发者_如何学JAVA .. how do i do it?

Thanks a lot for helping.


foreach ( $cclArray as $k => $array ) {
    if ( $array['url'] == 'test1.html' ) {
        unset($cclArray[$k]);
    }
}


If you are using PHP >5.3 you can do it simply like this:

$cclArray = array_filter($cclArray, function ($var) {
    return $var['url'] != 'test1.html';
});
  • array_filter()
  • Anonymous functions in PHP


if you make your array this way

    $cclArray['test.html'] = 9;
    $cclArray['test1.html'] = 10;
    $cclArray['test2.html'] = 11;

it will be possible to delete with just

$url = 'test.html';
unset($cclArray[$url]);


for ($i=0;$i<count($cclArray);$i++)
  if($cclArray[$i]['url']=='test.html') unset($cclArray[$i]['url'])


foreach($cclArray as $key=>$val){
  if($val['url'] == 'test1.html'){
   unset($cclArray[$key]);
  }
}

I think this is it.


for($i=0; $i<count($cclArray); $i++){
    if('test1.html' === $cclArray[$i]['url']){
        array_splice($cclArray, $i, 1);
    }
}

This is better but remember that unset() does not remove actual element it just sets it to null. If you want it to be complete gone, then after the unset() you should also do this: $cclArray = array_filter($cclArray);

Or you can do this in order to complete remove the array element instead of just unsetting it

for($i=0; $i<count($cclArray); $i++){
if('test1.html' === $cclArray[$i]['url']){
array_splice($cclArray, $i, 1);
}

}

0

精彩评论

暂无评论...
验证码 换一张
取 消