在 PHP 中根据一些重复值对数组进行排序

发布于 2024-12-12 04:57:51 字数 390 浏览 0 评论 0原文

我有一个包含以下格式字符串的数组:

[0] => "title|url|score|user|date"
[1] => "title|url|score|user|date"
[2] => "title|url|score|user|date"
[3] => "title|url|score|user|date"
...

score 字段是一个并不总是唯一的 int (例如,多个条目的分数可以为 0)。我希望根据字符串的 score 值对该数组中的字符串进行排序。最初,我尝试迭代数组并使用与投票分数相对应的键创建一个新数组。我很快意识到数组中不能有重复的键。

有没有一个好的干净的方法来做到这一点?

I have an array containing strings of this format:

[0] => "title|url|score|user|date"
[1] => "title|url|score|user|date"
[2] => "title|url|score|user|date"
[3] => "title|url|score|user|date"
...

The score field is an int that is not always unique (for example, more than one entry can have a score of 0). I'm looking to sort the strings in this array based on their score value. Originally, I tried iterating through the array and making a new one with keys corresponding to the vote score. I soon realized that you can't have duplicate keys in an array.

Is there a good clean way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

德意的啸 2024-12-19 04:57:51
$array = array(
    0 => "title|url|12|user|date",
    1 => "title|url|0|user|date",
    2 => "title|url|13|user|date",
    3 => "title|url|0|user|date"
);

function sortOnScore( $a, $b )
{
    // discard first two values
    list( ,,$scoreA ) = explode( '|', $a );
    list( ,,$scoreB ) = explode( '|', $b );

    return $scoreA == $scoreB ? 0 : ( $scoreA > $scoreB ? 1 : -1 );
}

usort( $array, 'sortOnScore' );

var_dump( $array );
$array = array(
    0 => "title|url|12|user|date",
    1 => "title|url|0|user|date",
    2 => "title|url|13|user|date",
    3 => "title|url|0|user|date"
);

function sortOnScore( $a, $b )
{
    // discard first two values
    list( ,,$scoreA ) = explode( '|', $a );
    list( ,,$scoreB ) = explode( '|', $b );

    return $scoreA == $scoreB ? 0 : ( $scoreA > $scoreB ? 1 : -1 );
}

usort( $array, 'sortOnScore' );

var_dump( $array );
还给你自由 2024-12-19 04:57:51

查看 PHP 的 usort 函数

function score_sort($rec1, $rec2)
{
  return $rec1['score'] - $rec2['score'];
}

usort($score_array);

替换 ['score'] 然而,您从字符串中提取分数

Look into PHP's usort function

function score_sort($rec1, $rec2)
{
  return $rec1['score'] - $rec2['score'];
}

usort($score_array);

Replace ['score'] with however you are extracting the scores from the strings

安静 2024-12-19 04:57:51

首先,您需要使用 explode 将字符串转换为数组,以便可以进行比较:

// If using PHP >= 5.3, this can also be made into an anonymous function
function converter($string) {
    $result = array_combine(
        array('title', 'url', 'score', 'user', 'date'),
        explode('|', $string)
    );

    // When these are later compared, it should be as numbers
    $result['score'] = (int)$result['score'];
    return $result;
}

$input = array(
    'Foo|http://foo|0|user1|today',
    // etc.
);
$converted = array_map('converter', $input);

这将使 $converted 看起来像:

array (
  0 => array (
    'title' => 'Foo',
    'url' => 'http://foo',
    'score' => '0',
    'user' => 'user1',
    'date' => 'today',
  ),
)

然后您可以使用以下代码对数组进行排序我的回答此处轻松指定您想要的任何排序标准想:

usort($converted, make_converter('score', 'date', 'title'));

First you need to turn the strings into arrays with explode so you can do the comparisons:

// If using PHP >= 5.3, this can also be made into an anonymous function
function converter($string) {
    $result = array_combine(
        array('title', 'url', 'score', 'user', 'date'),
        explode('|', $string)
    );

    // When these are later compared, it should be as numbers
    $result['score'] = (int)$result['score'];
    return $result;
}

$input = array(
    'Foo|http://foo|0|user1|today',
    // etc.
);
$converted = array_map('converter', $input);

This will make $converted look like:

array (
  0 => array (
    'title' => 'Foo',
    'url' => 'http://foo',
    'score' => '0',
    'user' => 'user1',
    'date' => 'today',
  ),
)

Then you can sort the array using the code from my answer here by easily specifying any sort criteria you want:

usort($converted, make_converter('score', 'date', 'title'));
聽兲甴掵 2024-12-19 04:57:51

就我个人而言,我很想迭代数组,用 | 分割它并将其放入一个新的多维数组中,例如这样:

[0] => array([title]=>'title',[url]=>'url',[score]=>'score',[user]=>'user',[date]=>'date')
[1] => array([title]=>'title',[url]=>'url',[score]=>'score',[user]=>'user',[date]=>'date')

然后它就变得很容易排序,只需使用这样的函数:

function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {
         if(is_array($array) && count($array)>0) {
             foreach(array_keys($array) as $key) { 
                $temp[$key]=$array[$key][$index];
             }
             if(!$natsort) {
                 if ($order=='asc') {
                     asort($temp);
                 } else {    
                     arsort($temp);
                 }
             }
             else 
             {
                 if ($case_sensitive===true) {
                     natsort($temp);
                 } else {
                     natcasesort($temp);
                 }
                if($order!='asc') { 
                 $temp=array_reverse($temp,TRUE);
                }
             }
             foreach(array_keys($temp) as $key) { 
                 if (is_numeric($key)) {
                     $sorted[]=$array[$key];
                 } else {    
                     $sorted[$key]=$array[$key];
                 }
             }
             return $sorted;
         }
     return $sorted;
 }

即这样做:

$sortedarray = sortmulti($array,'score','asc');

Personally I'd be tempted to iterate through the array, split it by the |'s and put it into a new multi-dimensional array, for example something like this:

[0] => array([title]=>'title',[url]=>'url',[score]=>'score',[user]=>'user',[date]=>'date')
[1] => array([title]=>'title',[url]=>'url',[score]=>'score',[user]=>'user',[date]=>'date')

Then it becomes easy to sort, just use a function like this:

function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {
         if(is_array($array) && count($array)>0) {
             foreach(array_keys($array) as $key) { 
                $temp[$key]=$array[$key][$index];
             }
             if(!$natsort) {
                 if ($order=='asc') {
                     asort($temp);
                 } else {    
                     arsort($temp);
                 }
             }
             else 
             {
                 if ($case_sensitive===true) {
                     natsort($temp);
                 } else {
                     natcasesort($temp);
                 }
                if($order!='asc') { 
                 $temp=array_reverse($temp,TRUE);
                }
             }
             foreach(array_keys($temp) as $key) { 
                 if (is_numeric($key)) {
                     $sorted[]=$array[$key];
                 } else {    
                     $sorted[$key]=$array[$key];
                 }
             }
             return $sorted;
         }
     return $sorted;
 }

i.e. do this:

$sortedarray = sortmulti($array,'score','asc');
归途 2024-12-19 04:57:51

使用 asort 函数会非常容易:

$pattern = '#^([^|]+)\|([^|]+)\|([^|]+)\|([^|]+)\|([^|]+)$#';
$sorted = array();
foreach($data as $s) $sorted[] = preg_replace($pattern, '$3|$1|$2|$4|$5', $s);
asort($sorted);

这 4 行代码,当给定 $data: 时,

Array
(
    [0] => title_0|url_0|6|user_0|date_0
    [1] => title_1|url_1|6|user_1|date_1
    [2] => title_2|url_2|2|user_2|date_2
    [3] => title_3|url_3|3|user_3|date_3
    [4] => title_4|url_4|2|user_4|date_4
    [5] => title_5|url_5|7|user_5|date_5
    [6] => title_6|url_6|3|user_6|date_6
    [7] => title_7|url_7|8|user_7|date_7
    [8] => title_8|url_8|3|user_8|date_8
    [9] => title_9|url_9|9|user_9|date_9
)

将生成 $sorted:

Array
(
    [2] => 2|title_2|url_2|user_2|date_2
    [4] => 2|title_4|url_4|user_4|date_4
    [3] => 3|title_3|url_3|user_3|date_3
    [6] => 3|title_6|url_6|user_6|date_6
    [8] => 3|title_8|url_8|user_8|date_8
    [0] => 6|title_0|url_0|user_0|date_0
    [1] => 6|title_1|url_1|user_1|date_1
    [5] => 7|title_5|url_5|user_5|date_5
    [7] => 8|title_7|url_7|user_7|date_7
    [9] => 9|title_9|url_9|user_9|date_9
)

并且只需再多 2 行,您就可以将数组的每个元素中的项目恢复为原始顺序/格式:

$data = array();
foreach($sorted as $s) $data[] = preg_replace($pattern, '$2|$3|$1|$4|$5', $s);

将 $data 设置为:

Array
(
    [0] => title_2|url_2|2|user_2|date_2
    [1] => title_4|url_4|2|user_4|date_4
    [2] => title_3|url_3|3|user_3|date_3
    [3] => title_6|url_6|3|user_6|date_6
    [4] => title_8|url_8|3|user_8|date_8
    [5] => title_0|url_0|6|user_0|date_0
    [6] => title_1|url_1|6|user_1|date_1
    [7] => title_5|url_5|7|user_5|date_5
    [8] => title_7|url_7|8|user_7|date_7
    [9] => title_9|url_9|9|user_9|date_9
)

It would be very easy using the asort function:

$pattern = '#^([^|]+)\|([^|]+)\|([^|]+)\|([^|]+)\|([^|]+)$#';
$sorted = array();
foreach($data as $s) $sorted[] = preg_replace($pattern, '$3|$1|$2|$4|$5', $s);
asort($sorted);

these 4 lines of code, when given $data:

Array
(
    [0] => title_0|url_0|6|user_0|date_0
    [1] => title_1|url_1|6|user_1|date_1
    [2] => title_2|url_2|2|user_2|date_2
    [3] => title_3|url_3|3|user_3|date_3
    [4] => title_4|url_4|2|user_4|date_4
    [5] => title_5|url_5|7|user_5|date_5
    [6] => title_6|url_6|3|user_6|date_6
    [7] => title_7|url_7|8|user_7|date_7
    [8] => title_8|url_8|3|user_8|date_8
    [9] => title_9|url_9|9|user_9|date_9
)

will generate $sorted:

Array
(
    [2] => 2|title_2|url_2|user_2|date_2
    [4] => 2|title_4|url_4|user_4|date_4
    [3] => 3|title_3|url_3|user_3|date_3
    [6] => 3|title_6|url_6|user_6|date_6
    [8] => 3|title_8|url_8|user_8|date_8
    [0] => 6|title_0|url_0|user_0|date_0
    [1] => 6|title_1|url_1|user_1|date_1
    [5] => 7|title_5|url_5|user_5|date_5
    [7] => 8|title_7|url_7|user_7|date_7
    [9] => 9|title_9|url_9|user_9|date_9
)

and with just 2 more lines you can have the items in each element of the array back in the original order/format:

$data = array();
foreach($sorted as $s) $data[] = preg_replace($pattern, '$2|$3|$1|$4|$5', $s);

setting $data to:

Array
(
    [0] => title_2|url_2|2|user_2|date_2
    [1] => title_4|url_4|2|user_4|date_4
    [2] => title_3|url_3|3|user_3|date_3
    [3] => title_6|url_6|3|user_6|date_6
    [4] => title_8|url_8|3|user_8|date_8
    [5] => title_0|url_0|6|user_0|date_0
    [6] => title_1|url_1|6|user_1|date_1
    [7] => title_5|url_5|7|user_5|date_5
    [8] => title_7|url_7|8|user_7|date_7
    [9] => title_9|url_9|9|user_9|date_9
)
七色彩虹 2024-12-19 04:57:51

创建一个新的数组数组:

[0] => array("score", old_array[0])

然后排序。

Create a new array of arrays:

[0] => array("score", old_array[0])

Then sort.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文