I want to filter the data from the array in a loop. All i want to know is can I use the array_filter inside loop because i am using it and it is not working properly This is the array which i am getting from DB
Array
(
[0] => Chocolate Manufacturers,C
[1] => ,,,Chocolate Manufacturers,,Chocolate Manufacturers,,Chocolate Manufacturers
[2] =>
)
I am making the array unique by using this code
$num = 2;
for($i=0;$i<count($listing);$i++){
//echo var_export($listing[$i]->cat_title).'<br>';
$listing_cat[$i] = rtrim(ltrim($listing[$i]->cat_title,','),',');
$listing_cat[$i] = explode(',', $listing_cat[$i]);
//$listing_cat[$i] = array_filter(array_keys($listing_cat[$i]), function ($k){ return strlen($k)>=3; });
$listing_cat[$i] = array_filter($listing_cat[$i], function ($sentence){
//divide the each sentence in words
$words = explode(',',$sentence);
$resSentence = [];
//check each words if their length is more then $num
foreach($words as $word){
if(strlen($word) > $num){
$resSentence[] = $word;
}
}
return implode(' ', $resSentence);
});
$listing_cat[$i] = array_unique($listing_cat[$i]);
$listing_cat[$i] = implode(',', $listing_cat[$i]);
$listing_cat[$i] = rtrim(ltrim($listing_cat[$i],','),',');
//$tags['title'][$i] = rtrim(ltrim($listing[$i]->cat_title,','),',');
}
After running this code result is showing like this
Array (
[0] => Chocolate Manufacturers,C
[1] => Chocolate Manufacturers
[2] =>
)
But what i want is to remove the C from the first array i mean to say the unwanted string or string which length will be less than 2 i want to remove that.
Expected Result:
Array (
[0] => Chocolate Manufacturers
[1] => Chocolate Manufacturers
[2] =>
)
i used the below function to remove
$NUM = 2;
$listings[$i] = array_filter($listings[$i], function ($element){
return ($element[$i] > $NUM);
});
But i think because it is in loop it is not working properly. I am placing this code above the array_unique
line in loop. All i want is to remove the value which length will be less than 2.
Finally i have achieved my desired answer
$num = 2;
for ($i = 0; $i < count($listing); $i++) {
//$listing_cat[$i] = array_unique($listing[$i]->cat_title);
$listing_cat[$i] = rtrim(ltrim($listing[$i]->cat_title, ','), ',');
$sentence = $listing_cat[$i];
//divide the each sentence in words
$words = explode(',', $sentence);
$resSentence = [];
//check each words if their length is more then $num
foreach ($words as $word) {
if (strlen($word) > $num) {
$resSentence[] = $word;
}
}
$listing_cat[$i] = array_unique($resSentence);
$listing_cat[$i] = implode(',',$listing_cat[$i]);
$listing_cat[$i] = rtrim(ltrim($listing_cat[$i],','),',');
}
echo '<pre>';
print_r($listing_cat);
echo '</pre>';
it is showing perfect result what i want
Array (
[0] => Chocolate Manufacturers
[1] => Chocolate Manufacturers
[2] =>
)
Thanks all for help really appriciated