duanji5569 2018-05-31 14:51
浏览 70
已采纳

PHP数组长度

So this may be a bit long winded to explain, but I'll try to make it concise.

I have a db query that pulls in 3 different Tag IDs, 2 of them are associated to 4 Hub IDs, while 1 is associated with only 3.

I return all tags, and sort the results by ID (so all 4 results for tag 1 are grouped, all 4 of 2, and all 3 of 3) Like so:

Array
    (
        [0] => 40BD32751DF1
        [1] => 40BD32751DF1
        [2] => 40BD32751DF1
        [3] => 40BD32751DF1
        [4] => 10CEA9FD173A
        [5] => 10CEA9FD173A
        [6] => 10CEA9FD173A
        [7] => 10CEA9FD173A
        [8] => 10CEA9FCFE26
        [9] => 10CEA9FCFE26
        [10] => 10CEA9FCFE26
    )

Then I do a while loop and loop it for each Tag ID (3x). Inside that, I use array_keys on an array_column search to find the array indexes of each Tag ID, count how many results I have (4, 4, 3) I then take that row's data using the array key, and loop number to push that row of data into an array for later sorting:

while($currentTag = pg_fetch_assoc($tagList)) {
    $tkeys = array_keys(array_column($tagDataArray, 'devmac'), $currentTag['devmac']);
    $tempArray = array();
    for($k=0; $k < count($tkeys); $k++){
        array_push($tempArray, $tagDataArray[$tkeys[$k]]);
    }

//Then I sort that temporary array so one of the values in the row is the highest:

    foreach($tempArray as $sigkey => $sigrow) { 
        $sigsort[$sigkey] = $sigrow['devrssi']; 
    }
    array_multisort($sigsort, SORT_DESC, $tempArray);
    updateArticles($tempArray[0]);
}

Now the problem comes from that temporary array. I have 4 results for the first ID, 4 for the second, then 3 for the third, yet for the third ID, somehow I still get 4 items in the array even though I reinitialize it with each while loop pass (each ID). The fourth result from the second ID, ends up as the fourth result for the third ID.

How is this possible? I've been trying to figure this out for hours and I'm not making any headway. The $tkeys gives me 3 on the third ID, so the for loop runs 3 times, everything makes sense, till the array push where something just decides to stick around. I've even added a print_r to the tempArray and before it runs the third time, it's empty! I dont get where it keeps creeping back in.

Thanks.

  • 写回答

1条回答 默认 最新

  • doulu1968 2018-05-31 15:06
    关注

    Make sure that when you process data in subsequent loops, you remove all previous data...

    $sigsort= [];
    foreach($tempArray as $sigkey => $sigrow) { 
        $sigsort[$sigkey] = $sigrow['devrssi']; 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗