0

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] => →
    ) 
is_numeric
  • 187
  • 2
  • 13
  • 1
    This might help you if you want a function to do it for you: http://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another – hlh3406 Mar 16 '15 at 11:07
  • 1
    I would build a second array and push the objects to it in the order you want. – ambe5960 Mar 16 '15 at 11:18

1 Answers1

0

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 )
)
Harshita
  • 21
  • 3