-1

I have a multidimensional array like this:

$array = array(

    "hello" => "hola",

    "another_array" => array(
        "key" => "best key ever",
        "another" => "yes, another key",
     ),

    "coolarray" => array(
        "bool" => true,
        "string" => "this is a string!",
    ),
);

I want a class like this:

class MyClass {

    public $array;

    public function __construct($array) {
        // something
        $this->array_to_xml($array);
    }

    public function array_to_xml($array) {
        // convert array to xml
    }

Then I want to be able to do things like this:

$string = $this->array->coolarray->string;

How can I do that?

James
  • 261
  • 2
  • 5
  • 16
  • @Martijn I have tried 3 of the answers in that and I still don't know how to use it as an object like this: `$string = $this->array->coolarray->string;` – James Feb 10 '14 at 17:52

1 Answers1

1

This gets asked a lot

Not sure why you mention XML, sounds like you just want an object.

See this answer for example: https://stackoverflow.com/a/11854285/543455

$obj = json_decode(json_encode($array));

Community
  • 1
  • 1
edmondscommerce
  • 2,001
  • 12
  • 21
  • Never used JSON before. I'll give that a go. I mentioned XML because I'm making my own version of an open-source project which uses XML conversion. I tried to modify it and I broke it. – James Feb 10 '14 at 17:57
  • Update: It's saying that I'm trying to get a property of a non-object. – James Feb 10 '14 at 18:01
  • Okay, this is very bad practie. Look at this answer: http://stackoverflow.com/a/4790485/801496 It's much better way. – ozahorulia Feb 10 '14 at 19:19
  • I'm reserving judgement on the bad practice call. Two built in function calls versus recursive user land functions, I'm honestly not sure what is the best approach and i suspect it largely depends on the array you are converting – edmondscommerce Feb 10 '14 at 20:43