-3

I have the following object:

'new_value' => 
    'name' => 'Teste',
    'key' => 'TESTE',
    'icon' => 'empty',

And the following array:

array(
   0 => 'name',
   1 => 'icon',
   2 => 'key',
)

However I would like to arrange the properties in the object based in the value of the array, so the result would be:

'new_value' => 
    'name' => 'Test',
    'icon' => 'empty',
    'key' => 'TEST', 

How can I achieve this? I couldn't find anything on google related to this, only how to sort an array of objects.

Mathias Hillmann
  • 1,537
  • 2
  • 13
  • 25
  • 1
    Object doesn't have ordered properties as far as I know. Also, the first one of the code examples doesn't look like an object at all. Perhaps this question is what you are looking for https://stackoverflow.com/questions/44200772/php-change-order-of-object-properties – Dharman Jan 18 '21 at 15:06
  • Assuming stdClass objects, the most you can do is create a new object with properties in the desired order, based on your array, and then add values from your old object into it. Object properties can't be reordered like array keys. – Markus AO Jan 18 '21 at 15:10
  • Iterate your sorting array and recreate the array/object from the original. – El_Vanja Jan 18 '21 at 15:37
  • @MarkusAO That worked, could you please add an answer so I can mark it as correct? – Mathias Hillmann Jan 18 '21 at 16:23
  • @MathiasHillmann sure, I've fluffed it out into an answer. Glad it helped. – Markus AO Jan 18 '21 at 19:01

1 Answers1

2

Object properties can't be reordered like array keys. You will have to create a new blank object (assuming stdClass objects), and then add in the properties in the desired order. First, let's recreate the source object:

$old_obj = (object) [
    'name' => 'Teste',
    'key' => 'TESTE',
    'icon' => 'empty'
];

Then, here's your new order:

$new_order = [
   'name',
   'icon',
   'key'
];

Then, we create a new object and add the properties in the desired order:

$new_obj = new stdClass();

foreach($new_order as $prop) {
    $new_obj->$prop = $old_obj->$prop;
}

This results in:

object(stdClass)#3 (3) {
    ["name"] · string(5) "Teste"
    ["icon"] · string(5) "empty"
    ["key"] · string(5) "TESTE"
}

If you need to do this often, turn the operation into a helper function:

function reorder_props(object $obj, array $order) {
    $new_obj = new stdClass();
    foreach($order as $prop) {
        $new_obj->$prop = $obj->$prop;
    }
    return $new_obj;
}

Another approach would be to create an associative array with the keys in the desired order, and then cast it into a stdClass object (as we did in instantiating your source object). You could also use the above function/logic for reordering array keys with very minor modifications.

Markus AO
  • 4,771
  • 2
  • 18
  • 29