-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?

1
  • @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; Commented Feb 10, 2014 at 17:52

1 Answer 1

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));

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Update: It's saying that I'm trying to get a property of a non-object.
Okay, this is very bad practie. Look at this answer: stackoverflow.com/a/4790485/801496 It's much better way.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.