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

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集