我有一个数组:
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"
]
]
然后拆分它。但是我不确定如何比较这个新数组中的这两个元素。由于现在6
的最后 2 个元素可能会随着添加更多数据而更改7
。我基本上需要判断第一个元素是否大于、小于或等于第二个元素。
你可以使用内置的end()函数,然后使用prev():
if (end($chart_data) == prev($chart_data)) {
echo 'Two last elements of an array are equal!';
}
将最后一个变量传递为假;
preserve_keys 请注意,默认情况下,array_slice() 将重新排序和重置数字数组索引。您可以通过将preserve_keys设置为 TRUE 来更改此行为。
array_slice($chart_data, -2, 2, false);
你已经输出了这个数组
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";
如果从以前的代码中获取的数组称为 $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>";
}
如果适合您,您可以使用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.";
}