douzhao9608 2018-10-24 12:41
浏览 66
已采纳

PHP嵌套foreach获取数组的唯一大小[重复]

This question already has an answer here:

Here is the situation: There are thousand of data. But not all of that are unique. The first foreach loop is unique. So, I am putting the size in a Array . Next loop might have same size. So, I am checking the size of a variable. If the size found in the Array , that means its not unique otherwise the size of that variable would be in the Array. The problem is I'm getting common and unique (both) size in the Array.

PHP Code:

$counter = array();
foreach ($result_all as $data){
    $message =  $data['msg'];
    $size_of_message = strlen($message);

    if(contains($message,$chittagong)){
       if(empty($counter)){
           $counter[] = $size_of_message;
       }else{
           foreach($counter as $a) {
               if ($size_of_message !== $a)
                   $counter[] = $size_of_message;
           }
       }
    }
}

Result:

Array
(
    [0] => 153
    [1] => 122
    [2] => 165
    [3] => 165
)

The result I am expecting:

Array
(
    [0] => 153
    [1] => 122
    [2] => 165
)
</div>
  • 写回答

4条回答 默认 最新

  • doushang7209 2018-10-24 12:54
    关注

    The problem lies here:

               foreach($counter as $a) {
                   if ($size_of_message !== $a)
                       $counter[] = $size_of_message;
               }
    

    You are comparing $size_of_message with every existing element, and for most of them if statement will return true, adding new element to counter. And you want to add it only if no element matches it. So you need to use in_array() function instead of foreach:

    if (!in_array($size_of_message, $counter) {
      $counter[] = $size_of_message;
    }
    

    In this case you also don't need to check if array is empty.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?