0

我有一个具有 3 个属性的对象。我想输入一个数字 1,2 或 3(0,1 或 2 也可以)并根据其属性值按升序对对象进行排序。

这是我的对象的样子:

var_dump($obj);

array(3) { 
    [0]=> object(stdClass)#25 (92) { 
        ["file_id"]=> string(1) "6" 
        ["name"]=> string(1) "1st item" 
    } 
    [1]=> object(stdClass)#26 (92) { 
        ["file_id"]=> string(1) "7"    
        ["name"]=> "2nd item"
    } 
    [2]=> object(stdClass)#27 (92) { 
        ["file_id"]=> string(1) "8" 
        ["name"]=> "3rd item"
    }
}

如果我输入 1,那么输出将如下所示:

file_id    name
 6      1st item
 7      2nd item
 8      3rd item

如果我输入 2,那么输出将是:

7  2nd item
8  3rd item
6  1st item

如果我输入 3,那么输出将是:

8  3rd item
6  1st item
7  2nd item

这个问题与我之前在 Stackoverflow 上提出的问题几乎相同,唯一的例外是我需要sort()在值的索引位置上file_id而不是在file_id值本身上。即,我需要对 1,2,3 而不是 6,7,8 进行排序。

如果您对这个问题特别兴奋(是的,我意识到这不太可能),我很想知道输出中的数字2592代表什么:object(stdClass)#25 (92).

4

3 回答 3

2

我想你正在寻找usort

写3个比较函数,每个属性一个,根据输入值切换,使用哪个比较函数

编辑:数字是 PHP 内部对象 id ( #25) 和对象的大小。

快速示例:

function compare_1($a, $b) {
  return strcmp($a->file_id, $b->file_id);
}
// compare_2, compare_3 accordingly as needed with your objects

switch ($input) {
  case 1:
    $compareFunctionName = 'compare_1';
    break;
  case 2:
    $compareFunctionName = 'compare_2';
    break;
  case 3:
    $compareFunctionName = 'compare_3';
    break;
  default:
    throw new Exception('wrong Parameter: input is ' . $input);
 }

 usort($objectArray, $compareFunctionName);

 var_dump($objectArray);
于 2012-08-13T13:12:09.693 回答
1

据我了解,在按某些属性对数组进行排序,您希望旋转数组,以便例如数组 (1,2,3,4) 变为 (3,4,1,2)。
在此示例中,我使用字符串文字作为数组成员,切换到对象是微不足道的。

<?php
$sortedData = array('A', 'B', 'C', 'D', 'E'); // getting an array like this has been solved by the answers to your previous question
$foo = rotate($sortedData, 2);
var_dump($foo);


function rotate($source, $n) {
    // could use some pre-checks...
    return array_merge(
        array_slice($source, $n, NULL, true),
        array_slice($source, 0, $n, true)
    );
}

印刷

array(5) {
  [0]=>
  string(1) "C"
  [1]=>
  string(1) "D"
  [2]=>
  string(1) "E"
  [3]=>
  string(1) "A"
  [4]=>
  string(1) "B"
}
于 2012-08-13T13:35:19.237 回答
0

这是完成此任务的简单算法

Step1:从数组array_search()中删除输入索引的值并取消设置函数

Step2:使用排序函数对数组进行排序

第 3 步:使用 push/pop 函数将删除的值添加到数组的顶部

有关数组函数的更多知识,请访问http://www.phpsyntax.blogspot.com

于 2012-08-13T13:38:34.860 回答