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条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据