2

Ive got this snippet of code below which works perfectly fine. I have been profiling it and the bit of code gets used alot of times, so I want to try figure out how to write it in a way that will perform better than the current way its written.

Is there a more efficient way to write this?

function objectToArray($d) {
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
        $d = get_object_vars($d);
    }

    if (is_array($d)) {
        // Return array converted to object Using __FUNCTION__ (Magic constant) for recursive call
        return array_map(__FUNCTION__, $d);
    }
    else {
        // Return array
        return $d;
    }
}
1
  • 1
    Convert to json, then convert to associative array? Commented Sep 23, 2013 at 22:10

5 Answers 5

1

You could implement a toArray() method to the class that needs to be converted:

e.g.

class foo
{
  protected $property1;
  protected $property2;

  public function __toArray()
  {
    return array(
      'property1' => $this->property1,
      'property2' => $this->property2
    );
  }
 }

Having access to the protected properties and having the whole conversion encapsulated in the class is in my opinion the best way.

Update

One thing to note is that the get_object_vars() function will only return the publically accessible properties - Probably not what you are after.

If the above is too manual of a task the accurate way from outside the class would be to use PHP (SPL) built in ReflectionClass:

$values = array();
$reflectionClass = new \ReflectionClass($object);
foreach($reflectionClass->getProperties() as $property) {
  $values[$property->getName()] = $property->getValue($object); 
}
var_dump($values);
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks AlexP, would that be able to be put in instad of the current snippet?
@ChrisEdington Take a look at my update. Either option will work, it just depends on the scope you are trying to access the variables from and the feasibility of adding new methods to the class.
Would it be able to keep the same function structure & name and just rework the code inside? The object being converted is a SOAP response, if that helps?..
Yep, all you need to do is add a method as explained, no other changes in the class would be needed. You will however need to add to the array every time you add a new property - unless you generate the array dynamically - Which should be easy (having access to $this directly).
Perhaps something like using $array = json_decode(json_encode($object), true); in that function structure?
|
0

depends what kind of object it is, many standard php objects have methods built in to convert them

for example MySQLi results can be converted like this

$resultArray = $result->fetch_array(MYSQLI_ASSOC);

if its a custom class object you might consider implementing a method in that class for that purpose as AlexP sugested

2 Comments

Would it be able to keep the same function structure & name and just rework the code inside? The object being converted is a SOAP response, if that helps?..
Not familiar with SOAP specifically, but a quick google reviled its XML so you can use PHP's XML functions $soapResponce = simplexml_load_file("soapResponce.xml"); $soapArray = unserialize(serialize(json_decode(json_encode((array) $soapResponce), 1))); print_r($xml_array); credit: stackoverflow.com/questions/12148662/xml-to-array-php
0

Ended up going with:

function objectToArray($d) {
$d = (object) $d;
return $d;
}
function arrayToObject($d) {
$d = (array) $d;
return $d;
}

Comments

0

As AlexP said you can implement a method __toArray(). Alternatively to ReflexionClass (which is complex and expensive), making use of object iteration properties, you can iterate $this as follow

class Foo
{
  protected $var1;
  protected $var2;

  public function __toArray()
  {
    $result = array();
    foreach ($this as $key => $value) {
      $result[$key] = $value;
    }
    return $result;
  }
}

This will also iterate object attributes not defined in the class: E.g.

$foo = new Foo;
$foo->var3 = 'asdf';
var_dump($foo->__toArray());)

See example http://3v4l.org/OnVkf

Comments

0

This is the fastest way I have found to convert object to array. Works with Capsule as well.

     function objectToArray ($object) {
        return json_decode(json_encode($object, JSON_FORCE_OBJECT), true);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.