遍历一个数组并将当前键值对与下一个php进行比较

时间:2016-07-20 08:15:28

标签: php arrays loops while-loop

我试图比较一个数组的键值对来比较下一个键值对以找到较低的一个值。如果发现较低的一个是未设置并向前移动。但是我没有得到准确性,这里有什么问题,请建议。这是代码。 这是要进行比较和评估的阵列。

Array
(
[0] => Array
    (
        [com_details] => Array
            (
                [spid] => 6

            )

        [distance] => 13.1 mi
    )

[1] => Array
    (
        [com_details] => Array
            (
                [spid] => 6

            )

        [distance] => 66.2 mi
    )

[2] => Array
    (
        [com_details] => Array
            (
                [spid] => 6

            )

        [distance] => 1.5 mi
    )

[3] => Array
    (
        [com_details] => Array
            (
                [spid] => 7

            )

        [distance] => 188 mi
    )

[4] => Array
    (
        [com_details] => Array
            (
                [spid] => 7

            )

        [distance] => 96.7 mi
    )

[5] => Array
    (
        [com_details] => Array
            (
                [spid] => 7

            )

        [distance] => 3.1 mi
    )

[6] => Array
    (
        [com_details] => Array
            (
                [spid] => 14

            )

        [distance] => 1.8 mi
    )

[7] => Array
    (
        [com_details] => Array
            (
                [spid] => 14

            )

        [distance] => 228 mi
    )

[8] => Array
    (
        [com_details] => Array
            (
                [spid] => 14

            )

        [distance] => 82.2 mi
    )

)

在上面的数组中,我需要比较spid相同但距离不同的com_details,如果下一个或上一个距离很小,那么另一个将被取消设置并向前移动以进行下一次迭代。但是我没有达到这个目的。

$l=0;
    do{
        $length = count($dispatch_locations1);
        if($length >= $l+1){
            if($dispatch_locations1[$l]['com_details']['spid'] == @$dispatch_locations1[$l+1]['com_details']['spid']){
               if($dispatch_locations1[$l]['distance'] > $dispatch_locations1[$l+1]['distance']){
                   unset($dispatch_locations1[$l]);
                   $l--;
                  $dispatch_locations1 =  array_values($dispatch_locations1);
               } else if($dispatch_locations1[$l]['distance'] < $dispatch_locations1[$l+1]['distance']){
                   unset($dispatch_locations1[$l+1]);
                   $l--;
                  $dispatch_locations1 =  array_values($dispatch_locations1);
      } else if($dispatch_locations1[$l]['distance'] == $dispatch_locations1[$l+1]['distance']){
                   unset($dispatch_locations1[$l+1]);
                   $l--;
                  $dispatch_locations1 =  array_values($dispatch_locations1);
      }
            }
        }
            $l++;
        } while ($l <= count($dispatch_locations1)+1);
    }

在完整的迭代后得到这个数组有点不对。

Array
(
[0] => Array
    (
        [com_details] => Array
            (
                [spid] => 6

            )

        [distance] => 1.5 mi
    )

[1] => Array
    (
        [com_details] => Array
            (
                [spid] => 7

            )

        [distance] => 188 mi
    )

[2] => Array
    (
        [com_details] => Array
            (
                [spid] => 14

            )

        [distance] => 1.8 mi
    )

)

在此结果中,返回的第二个数组距离为188,这是错误的。

请在此处说明我的错误。

2 个答案:

答案 0 :(得分:1)

您可以通过删除代码来简化整个复杂操作。下面的代码片段演示了如何,但在开始之前,您可能想要尝试&amp;自己测试here

此处使用的样本阵列用于测试

<?php

    $arrMain        = array(
        array(
            'com_details'   => array('spid'=> 6),
            'distance'      => "13.1mi",
        ),
        array(
            'com_details'   => array('spid'=> 6),
            'distance'      => "66.2 mi",
        ),
        array(
            'com_details'   => array('spid'=> 6),
            'distance'      => "1.5mi",
        ),
        array(
            'com_details'   => array('spid'=> 7),
            'distance'      => "188.0 mi",
        ),
        array(
            'com_details'   => array('spid'=> 7),
            'distance'      => "96.7 mi",
        ),
        array(
            'com_details'   => array('spid'=> 7),
            'distance'      => "3.1 mi",
        ),
        array(
            'com_details'   => array('spid'=> 14),
            'distance'      => "1.8 mi",
        ),
        array(
            'com_details'   => array('spid'=> 14),
            'distance'      => "228.0 mi",
        ),
        array(
            'com_details'   => array('spid'=> 14),
            'distance'      => "82.2 mi",
        ),
    );

算法

<?php
    $arrSections    = array();

    // SORTING FUNCTION - USED TO SORT ARRAY VALUES BY "distance"
    // IN DESCENDING ORDER...
    function sortByField($prev, $next, $field="distance") {
        $prevVal = floatval(preg_replace("#[a-zA-Z\s\t]*#", "",$prev[$field]));
        $nextVal = floatval(preg_replace("#[a-zA-Z\s\t]*#", "",$next[$field]));
        return $prevVal - $nextVal;
    }

    // BUNDLE ARRAYS WITH SIMILAR spid INTO ONE GROUP
    // THUS CREATING A MULTI-DIMENSIONAL ARRAY WHOSE MAIN KEYS CORRESPOND TO
    // THE spid OF MEMBER ARRAYS IN THE GROUP. 
    foreach($arrMain as $iKey=>$subMain){
        $spID   = $subMain['com_details']['spid'];
        $strID  = $spID; 

        if(!array_key_exists($strID, $arrSections)) {
            $arrSections[$strID] = array();
        }
        $arrSections[$strID][] = $subMain;
    }

    // SORT THE ARRAY SIMPLY BY THE FIELD "distance" IN DESCENDING ORDER
    array_walk($arrSections, function (&$data) {
        usort($data, "sortByField");
    });

    // ARRAY THAT HOLDS THE DESIRED RESULT
    $arrFinal = array();

    // WE KNOW THAT ONLY THE FIRST ITEM IN THE ARRAY IS OF IMPORTANCE TO US
    // SO WE REMOVE ALL OTHER ITEMS EXCEPT THE 1ST...
    foreach($arrSections as $intKey=>&$section){
        array_splice($section, 1);
        $arrFinal[]   = $section[0];

    }
    var_dump($arrFinal);

VAR_DUMP的结果()

    // var_dump($arrSections); PRODUCES:::
    array (size=3)
      0 => 
        array (size=2)
          'com_details' => 
            array (size=1)
              'spid' => int 6
          'distance' => string '1.5mi' (length=5)
      1 => 
        array (size=2)
          'com_details' => 
            array (size=1)
              'spid' => int 7
          'distance' => string '3.1 mi' (length=6)
      2 => 
        array (size=2)
          'com_details' => 
            array (size=1)
              'spid' => int 14
          'distance' => string '1.8 mi' (length=6)

答案 1 :(得分:0)

如果我正确地解决了你的问题,那么解决这个问题的代码就是......

此代码首先按spid而不是距离对数组进行排序:

<?php
usort($dispatch_locations1, function($a, $b) {
    if($a['com_details']['spid'] > $b['com_details']['spid']) {
        return 1;
    } elseif($a['com_details']['spid'] < $b['com_details']['spid']) {
        return -1;
    }

    return (floatval($a['distance']) < floatval($b['distance'])) ? -1 : 1;
});
?>