I have an array of products and i need to remove all of them which have a reference to webinar
The PHP version I am using is 5.2.9
$category->products
example:
[6] => stdClass Object
(
[pageName] => another_title_webinar
[title] => Another Webinar Title
)
[7] => stdClass Object
(
[pageName] => support_webinar
[title] => Support Webinar
)
[8] => stdClass Object
(
[pageName] => support
[title] => Support
)
In this case number 8 would be left but the other two would be stripped...
Could anyone help?
In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically. Function Used: unset(): This function unsets a given variable.
1) Remove duplicates from an array using a Set To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
Check out array_filter(). Assuming you run PHP 5.3+, this would do the trick:
$this->categories = array_filter($this->categories, function ($obj) {
if (stripos($obj->title, 'webinar') !== false) {
return false;
}
return true;
});
For PHP 5.2:
function filterCategories($obj)
{
if (stripos($obj->title, 'webinar') !== false) {
return false;
}
return true;
}
$this->categories = array_filter($this->categories, 'filterCategories');
You can try
$category->products = array_filter($category->products, function ($v) {
return stripos($v->title, "webinar") === false;
});
Simple Online Demo
You could use the array_filter method. http://php.net/manual/en/function.array-filter.php
function stripWebinar($el) {
return (substr_count($el->title, 'Webinar')!=0);
}
array_filter($category->products, "stripWebinar")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With