PHP:根据对象属性值之一的索引位置对对象进行排序


PHP: sort an object on the index positions of one of its property values

>我有一个具有 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) .

我想你正在寻找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);

正如我理解您在按某些属性对数组进行排序的问题,您希望旋转数组,以便例如数组 (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"
}

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

步骤1:从数组array_search()和unset函数中删除输入索引的值

步骤2:使用排序函数对数组进行排序

步骤 3:使用推送/弹出功能将删除的值添加到数组顶部

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