简体   繁体   English

如何在循环中使用array_filter

[英]How to use array_filter in loop

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_filter吗,因为我正在使用它并且它无法正常工作,这是我从数据库中获得的数组

   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. 但是我想要的是从第一个数组中删除C,我的意思是说不需要的字符串或长度小于2的字符串,我想删除它。

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. 我将此代码循环放置在array_unique行上方。 All i want is to remove the value which length will be less than 2. 我只想删除长度小于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 谢谢大家的帮助

First of all: I recommend you not to use $listing along with $listings as variable names as it can easily lead to confusion and is not a good readability (especially confusing here on StackOverflow). 首先:我建议您不要将$listing$listings用作变量名,因为它很容易导致混淆,并且可读性不佳(尤其是在StackOverflow上引起混淆)。

Then: You have an error in your code. 然后:您的代码中有错误。 You are not checking for the length (count) but for the string itself which does resolve in TRUE. 您不是要检查长度(计数),而是要检查确实以TRUE解析的字符串本身。

You have: 你有:

$NUM = 2;

$listings[$i] = array_filter($listings[$i], function ($element){ 
    return ($element[$i] > $NUM);
    }
); 

You should have: 你应该有:

$NUM = 2;

$listings[$i] = array_filter($listings[$i], function ($element) use ($NUM) { 
    return (strlen($element[$i]) >= $NUM);
    }
); 

As you are code say, $listings is contains sentence. 正如您所说的, $listings包含句子。 If I got your problem properly then, you want to remove smaller from each sentences of the $listings variable. 如果我正确地解决了您的问题,那么您想从$listings变量的每个句子中删除较小的句子。 You can replace your this code: 您可以替换以下代码:

$NUM = 2;
$listings[$i] = array_filter($listings[$i], function ($element){ 
    return ($element[$i] > $NUM);
}); 

with the following codeblock: 使用以下代码块:

   $num = 2;
   $sentence = $listings[$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;
       }
   }
   $listings[$i] = implode(' ', $resSentence);

Update I have check out this program below, is it the whole think what you want? 更新我已经在下面查看了此程序,是您整体上想的吗?

<?php
$listing_cat = ['Chocolate Manufacturers,C', ',,,Chocolate Manufacturers,,Chocolate Manufacturers,,Chocolate Manufacturers', ''];
$num = 2;
for ($i = 0; $i < count($listing_cat); $i++) {

    $listing_cat[$i] = rtrim(ltrim($listing_cat[$i], ','), ',');
    $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] = implode($resSentence);
}
var_dump($listing_cat);

You may try the following code: 您可以尝试以下代码:

function arr_filter($arr, $min_length) {
    define('STR_MIN_LEN', $min_length);
    $arr = array_filter($arr);
    $arr_explode = [];

    foreach($arr as $value) {
        $arr_explode = explode(',', $value);
        $arr_explode = array_unique(array_filter($arr_explode));
        $arr_explode = array_filter($arr_explode, function($element) {
            return strlen($element) >= STR_MIN_LEN;
        });
    }

    return array_values(array_unique($arr_explode));
}

var_dump(arr_filter($arr, 2));

The above code is written as per your requirements. 上面的代码是根据您的要求编写的。 You could try it out and see if it works. 您可以尝试一下,看看是否可行。 This code may not be flexible. 此代码可能不灵活。 You can check it out with various test cases. 您可以使用各种测试用例进行检查。 Hope it works. 希望它能工作。

EDIT 编辑

I assume you have a multidimensional array like: 我假设您有一个多维数组,例如:

$arr = array(
    array(
        'Chocolate Manufacturers,C',
        ',,,Chocolate Manufacturers,,Chocolate Manufacturers,,Chocolate Manufacturers',
        ''
    ),
    array(
        'Ice Cream Manufacturers,C',
        ',,,Ice Cream Manufacturers,,Ice Cream Manufacturers,,Ice Cream Manufacturers',
        ''
    )
);

and the code is: 代码是:

function arr_filter($arr, $min_length) {
    define('STR_MIN_LEN', $min_length);
    $final_arr = array();

    foreach($arr as $value) {
        $value = array_filter($value);
        $arr_explode = [];

        foreach($value as $another_value) {
            $arr_explode = explode(',', $another_value);
            $arr_explode = array_unique(array_filter($arr_explode));
            $arr_explode = array_filter($arr_explode, function($element) {
                return strlen($element) >= STR_MIN_LEN;
            });
        }

        $final_arr[] = array_values(array_unique($arr_explode));
    }

    return $final_arr;
}

var_dump(arr_filter($arr, 2));

I've added this code to make it work with multidimensional array. 我添加了此代码,以使其可用于多维数组。 Hope it works for sure. 希望它可以正常工作。

EDIT 2 编辑2

function arr_filter($arr, $min_length) {
    define('STR_MIN_LEN', $min_length);
    $final_arr = array();

    foreach($arr as $value) {
        $value = array_filter($value);
        $arr_explode_final = [];

        foreach($value as $another_value) {
            $arr_explode = explode(',', $another_value);
            $arr_explode = array_filter($arr_explode, function($element) {
                return strlen($element) >= STR_MIN_LEN;
            });

            // the comma will be added if the string has two different words with comma-separated like `Chocolate Manufacturers, Ice Cream Manufacturers` else comma will be ommited
            $arr_explode_final[] = implode(',', array_unique($arr_explode)); 
        }

        $final_arr[] = $arr_explode_final;
    }
    return $final_arr;
}

var_dump(arr_filter($arr, 2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM