remove subarray with php

◇◆丶佛笑我妖孽 提交于 2019-12-13 23:13:26

问题


I have the following function and it's objective is to filter in the array tree those elements what are not conform to the search index and eliminate theme. I can get this function to bring the desired results.

public function negativeKeywordsFilter($products, $negative_keywords){
  $nk=explode(',',$negative_keywords);
  foreach ($products['productItems'] as $product){
    foreach ($product as $item){
        foreach ($nk as $word){
        if (stripos($item['name'],$word) !== false){
        unset($item);                       
    }

  }
}

}
 return $products;
}

My array looks as follows:

array(
    'page' => '1',
    'items' => '234',
    'items' => array(
        'item' => array(
            0 => array(
                'name' => 'second', 
                'description' => 'some description'
            )
        )
    )
)
)

If name is matching with the descriptions, then the value should be unset.


回答1:


the problem is you only unset a variable which has a copy of the value, you need to unset the corresponding element in the array.

public function negativeKeywordsFilter($products, $negative_keywords){
  $nk=explode(',',$negative_keywords);
  foreach ($products['productItems'] as $key1 => $product){
    foreach ($product as $key2 => $item){
        foreach ($nk as $word){
        if (stripos($item['name'],$word) !== false){
        unset($products['productItems'][$key1][$key2]);                       
    }

  }
}

}
 return $products;
}


来源:https://stackoverflow.com/questions/10835511/remove-subarray-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!