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.
Advertisement
Answer
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.