简体   繁体   English

在PHP中对对象数组进行自定义排序

[英]Custom Sorting an array of objects in PHP

I have a multi array containing objects. 我有一个包含对象的多数组。 How can I custom rearrange the objects in the array into the order I want? 如何自定义将数组中的对象重新排列为所需的顺序?

example move [approved] date above [action]... 例如将[批准]日期移到[操作]上方...

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [previous_ranking] => -
        [function_id] => 14
        [function] => SHE
        [entered] => 01/01/2002
        [description] => some text here.
        [m_likelihood] => 1
        [m_severity] => 4
        [m_score] => 4
        [m_rating] => Low
        [last_review] => 22/09/2014
        [action] => No change.
        [cost_comment] => 
        [approved] => 2012-10-30 10:36:12
        [status] => →
    ) 

Writing this function for sorting an array of objects. 编写此函数以对对象数组进行排序。 Objects contains data of different employee's name & age. 对象包含不同员工姓名和年龄的数据。 Hope this gives an idea for custom sorting of array of objects. 希望这能为自定义对象数组排序提供一个思路。

Code goes here: 代码在这里:

<?php
class Employee{
    private $name;
    public $age;

    public function assignData($empName, $empAge){
        $this->name = $empName;
        $this->age = $empAge;
    }

    public function displayData(){
        echo "\n Name of employee: ".$this->name; 
        echo "\n Age of employee: ".$this->age;
    }  
}

$emp1 = new Employee();
$emp1->assignData('Mayank',29);
//$emp1->displayData();

$emp2 = new Employee();
$emp2->assignData('Adesh',54);
//$emp2->displayData();

$emp3 = new Employee();
$emp3->assignData('Harshita',24);
//$emp3->displayData();

$empArr = array($emp1, $emp2, $emp3);
echo "Unsorted array of objects:";
print_r($empArr);

//Sorting them on basis of employee's age
for($i = 0; $i < (count($empArr)-1); $i++){
    for($j = $i+1; $j < count($empArr); $j++){
        if($empArr[$i]->age > $empArr[$j]->age){
            $temp = $empArr[$i];
            $empArr[$i] = $empArr[$j];
            $empArr[$j] = $temp;
        }
    }
}
echo "Sorted array of objects:";
print_r($empArr);
?>



Output:
Unsorted array of objects:
Array (
 [0] => Employee Object ( [name:Employee:private] => Mayank [age] => 29 )
 [1] => Employee Object ( [name:Employee:private] => Adesh [age] => 54 ) 
 [2] => Employee Object ( [name:Employee:private] => Harshita [age] => 24 )
)

Sorted array of objects:
Array (
 [0] => Employee Object ( [name:Employee:private] => Harshita [age] => 24 )
 [1] => Employee Object ( [name:Employee:private] => Mayank [age] => 29 )
 [2] => Employee Object ( [name:Employee:private] => Adesh [age] => 54 )
)

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

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