remove subarray with php

2019-09-28 04:37发布

问题:

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


标签: php arrays unset