// First, create an array of sub-arrays.
$arr = [
[1, 2, 3],
[1, 5, 6],
[3, 3, 4],
[1, 7, 8]
];
// We create a 'map' in PHP, which is basically just an array but with non-sequential (non-ordered) keys.
$map = [];
// We loop through all the sub-arrays and save the pair (first element, sub-array)
// since it's a 'map', it will only keep 1.
foreach($arr as $subarr)
{
// The 'idx' is the first element (sub-array[0])
$first = $subarr[0];
// If you want the first appearance of the first element (in this case [1,2,3] for '1')
// then you check if the first element of this sub-array was already found (is in the map)
if (!array_key_exists($first, $map))
$map[$first] = $subarr; // Set the
}
// Now we convert the 'map' into an array with sequential keys,
// since the 'map' is just an array with non-sequential keys.
$arr = array_values($map);
// You can print the output.
print_r($arr);
3条答案
按热度按时间dwthyt8l1#
你所要做的就是在每个子数组的
0
中的值上重新索引主数组,它将删除重复的值:这对你来说应该是有用的,甚至更好地与新的索引。但如果你想回到原来的样子,只需要得到的值(没有必要):
hk8txs482#
好吧,我找到解决办法了!
0aydgbwb3#
这是一个使用Map的解决方案,我认为这是一个非常有效的解决方案,因为它不是像双
foreach
那样的O(n^2)
复杂度,它只是O(n log n)
,它要快得多,我相信这是最快的复杂度。这种情况下的输出将是: