简体   繁体   English

在PHP中排序数组 - >需要一个好的算法

[英]Sorting an Array of Arrays in PHP --> Need a Good Algorithm

I have an array of 15000 elements each of which is an array of 4 elements. 我有一个15000个元素的数组,每个元素是一个包含4个元素的数组。 I want to sort by the second element of the 4. Originally I made the original array's keys the second element and then k-sorted but unfortunately, some of the second elements are duplicates and since one key can't refer to multiple elements i lost some elements in transition. 我想按照4的第二个元素排序。最初我把原始数组的键作为第二个元素然后k-sorted但不幸的是,一些第二个元素是重复的,因为一个键不能引用我丢失的多个元素转型中的一些要素。 I could bubble sort by the second element but I'm looking for something that runs at least on the order of nlog(n). 我可以通过第二个元素冒泡排序,但我正在寻找至少按nlog(n)顺序运行的东西。 Can anyone think of a good algorithm (or possibly a function in php that I don't know about) that can sort by the second element? 任何人都可以想到一个好的算法(或者可能是我不知道的php中的一个函数)可以按第二个元素排序吗? Thank you! 谢谢!

我认为你可以使用usort并定义cmp_function来使用第二个元素。

As others have stated, usort or uasort to maintain the array keys is what you want: 正如其他人所说, usortuasort维护数组键是你想要的:

<?php

$myArray = array(
    'fruits' => array(
        array('apples', 'oranges', 'bananas')              
    ),
    'vegetables' => array(
        array('lettuce', 'carrots', 'peas')
    ),
    'monkeys' => array(
        array('Curious George', 'Amy', 'Marcel')
    )
);

// PHP 5.3+ example using a closure

uasort($myArray, function(array $a, array $b) {
    // Use whatever sorting algorithm you like
    return strnatcasecmp($a[1], $b[1]); 
});

var_export($myArray);

Running the above will output: 运行以上将输出:

array (
  'monkeys' => 
  array (
    0 => 
    array (
      0 => 'Curious George',
      1 => 'Amy',
      2 => 'Marcel',
    ),
  ),
  'vegetables' => 
  array (
    0 => 
    array (
      0 => 'lettuce',
      1 => 'carrots',
      2 => 'peas',
    ),
  ),
  'fruits' => 
  array (
    0 => 
    array (
      0 => 'apples',
      1 => 'oranges',
      2 => 'bananas',
    ),
  ),
)

Here's an example that doesn't use a closure for pre PHP 5.3: 这是一个不在PHP 5.3之前使用闭包的示例:

sortFunc(array $a, array $b)
{
    return strnatcasecmp($a[1], $b[1]); 
}

uasort($myArray, 'sortFunc');

我不知道usort的内部实现是什么,但我敢打赌它比bubblesort更好(它可能是快速排序)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM