PHP Convert Array to Object

Just a quick one today, I’ve seen a few people asking how to convert an array to an object in PHP. All the responses to these questions seem to involve creating a recursive function to loop through the array and create corresponding properties in a stdClass for each key in the array.

There happens to be a MUCH simpler way built in to PHP from version 5.2, all you need to do is this:

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

This works because when you encode an array using JSON in PHP, non-numeric keys become object properties, so when the JSON string is convered back to an object, the new properties remain instead of being turned back into array keys.

Give it a try, it works perfectly.

- MB

Posted in: Programming by Matt Bearman on 27th April 2011 at 11:41 pm
Tags: , , , ,

PHP Super Accessor

I’m currently working on a little project using the twitter api, and part of it involves an object for tweets. Each instance of the tweet object has properties for ID, screen name of the author, the tweet text, time stamp, author’s profile picture, and the tweet it was posted in reply to. (more…)

Posted in: Programming by Matt Bearman on 1st October 2010 at 11:57 pm
Tags: , , ,

How to install Zend framework with XAMPP

I, like most web developers, use the excellent XAMPP to develop and test PHP/MySQL websites and applications on my local machine. The problem is the XAMPP doesn’t come with the Zend framework installed by default.

If you want to develop with Zend, you could always use Zend Server CE instead of XAMPP, as Zend Server comes with the Zend framework installed. The downside to that is that the Zend server is not as simple to set up and use as XAMPP, and if you’ve already been using XAMPP, migrating to Zend server can be a real pain in the ass, and you can’t run both XAMPP and Zend server together.

If you google installing Zend in XAMPP, there are many different guides, all of which seem overly complicated. Installing the zend framework under XAMPP is actually a lot simpler than most guides online would suggest, and using the following guide you should be able to run Zend Apps in your existing XAMPP environment in a matter of minutes. (more…)

Posted in: Programming by Matt Bearman on 18th May 2010 at 10:19 am
Tags: , , , ,

Time Sensitive Greeting

This is a quick tutorial on how I created the time sensitive greeting you see on the home page of this site. I created this in JavaScript so that it would use the viewers local time and not the server’s time, and if the viewer doesn’t have JavaScript enabled, it falls back to a simple “Hello”.

(more…)

Posted in: Programming by Matt Bearman on 22nd July 2009 at 8:02 am
Tags: , , ,