-4

If I have an array:

[my_name: 'Xavi', your_name: 'Luis']

And then I have an Object Name with properties: myName, yourName.

How could I best convert the array to the specified object? Is there anything out of the box available, some sort of helper class?

Brian Glaz
  • 15,468
  • 4
  • 37
  • 55
strangeQuirks
  • 4,761
  • 9
  • 40
  • 67

1 Answers1

1

It's not exactly a duplicate and the answer is not whatever @Alive_to_Die wrote - it sets the array index into exactly named class property, whilst the question is something else...

You will have to manually remap indexes into class properties.

class obj
{
    public $myName;
    public $yourName;
}

$array = [
    'my_name' => 'Xavi',
    'your_name' => 'Luis',
    ];

$obj = new obj;
$obj->myName = $array['my_name'];
$obj->yourName = $array['your_name'];

var_dump($obj);

Output:

object(obj)#1 (2) {
  ["myName"]=>
  string(4) "Xavi"
  ["yourName"]=>
  string(4) "Luis"
}
Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
  • That mapping is what I amasking for,is there a class i can see that does something similar, so convert underscore to camelcase and then sets the correct properties in an object – strangeQuirks Jan 10 '18 at 22:38
  • I would not recommend doing any automatic conversion. Either write your own converter or convert manually on the fly. If you use something like `str_replace` or something else, you'd be giving up vast control over your code. And doing things magically is generally a bad idea - harder debugging, harder maintenance, worse delegation ability of the code... – Kevin Kopf Jan 10 '18 at 22:40