如何比较数组的最后2个元素?

时间:2016-05-29 09:43:34

标签: php arrays compare

我有一个数组:

array:8 [▼
  0 => array:1 [▼
    "data" => "789"
  ]
  1 => array:1 [▼
    "data" => "800"
  ]
  2 => array:1 [▼
    "data" => "789"
  ]
  3 => array:1 [▼
    "data" => "787"
  ]
  4 => array:1 [▼
    "data" => "787"
  ]
  5 => array:1 [▼
    "data" => "787"
  ]
  6 => array:1 [▼
    "data" => "787"
  ]
  7 => array:1 [▼
    "data" => "787"
  ]
]

我需要取出数组的最后2个元素并进行比较。我尝试使用$getLast2 = array_slice($chart_data, -2, 2, true);获取最后2个。

array:2 [▼
  6 => array:1 [▼
    "data" => "787"
  ]
  7 => array:1 [▼
    "data" => "787"
  ]
]

然后拆分它。但我不知道如何比较这个新阵列中的这两个元素。现在67的最后两个元素可能会随着更多数据的添加而发生变化。我基本上需要判断第一个元素是否大于,小于或等于第二个元素。

5 个答案:

答案 0 :(得分:1)

您可以使用内置end()功能,然后使用prev()

if (end($chart_data) == prev($chart_data)) {
    echo 'Two last elements of an array are equal!';
}

答案 1 :(得分:0)

您已输出此数组

array:2 [▼
  6 => array:1 [▼
    "data" => "787"
  ]
  7 => array:1 [▼
    "data" => "787"
  ]
]

将它们重新编入索引以使用PHP array_values()函数

$outputedArray = array_values($outputedArray)
 if($outputedArray[0]['data'] > $outputedArray[1]['data'])
     echo "0 index is greater";

答案 2 :(得分:0)

  

将最后一个变量传递为false;

     
    

preserve_keys     请注意,array_slice()将默认重新排序并重置数值数组索引。您可以通过将preserve_keys设置为TRUE来更改此行为。

  
array_slice($chart_data, -2, 2, false);

答案 3 :(得分:0)

如果您从之前的代码中获得的数组被称为$splitArray,那么您可以执行以下操作:

list($array1, $array2) = $splitArray;
if ($array1['data']>$array2['data'])
{
  echo "1st is greater than 2nd<br>";
}
else
{
  echo "1st is not greater than 2nd<br>";
}

答案 4 :(得分:0)

如果它适合您,您可以使用array_pop以这种方式进行比较:

    <?php
        $array = [
            ["data" => "789"],
            ["data" => "800"],
            ["data" => "789"],
            ["data" => "787"],
            ["data" => "787"],
            ["data" => "789"],
            ["data" => "787"],
            ["data" => "787"],
        ];

    // MAKE A COPY OF THE ORIGINAL ARRAY:
    $arrayCopy      = $array;

    // POP THE LAST ELEMENT OFF THE $arrayCopy AND SAVE IT AS $lastElem:
    $lastElem       = array_pop($arrayCopy);

    // POP THE LAST ELEMENT OFF THE $arrayCopy AGAIN AND SAVE IT AS $beforeLastElem:
    $beforeLastElem = array_pop($arrayCopy);

    // NOW YOU CAN COMPARE THE LAST ELEMENT AND THE ONE BEFORE IT
    if($lastElem == $beforeLastElem){
        echo "The last 2 Elements of \$array are the same";
    }else{
        echo "The last 2 Elements of \$array are not identical.";
    }