Creating nice JSON strings on PHP

Hello everyone!

I spent some valuable time last night, trying to create a reliable algorithm to merge two arrays, so i can use PHP’s json_encode() for a simple logging class i’m writing, Loggy.

This morning, i found out that was unnecessary, turns out PHP’s array_combine() method could’ve got it all covered.

Let’s talk about the problem;

I had a “format” array, which has

{ "ID", "ip", "message", "tag", "date" }

in it. I read some data from a file, it is separated by a certain pattern. I created an array using explode() :

$entries = explode($separator, $line);

This produces an array like :

{ "LGY_123456", "10.23.231.221", "This is a dummy message", "Foo", "03.11.2013 12:11" }

I want these two arrays to be transformed into key-value pairs.

My first approach was, loop through the arrays using foreach and a counter; and create third array, which consumes more system resources and requires more time. The code follows.

// Creating a third array to put my key-value pairs in.
$tmp = array();
// A counter to iterate through the format array.
$i = 0;
foreach($entries as $entry) {
$tmp[$format[i]] = $entry;
$i++;
}
$output = json_encode($tmp);

As you see, the code looks messy and it’s a long way to go, looping through all the contents.

Now, i’m using

array_combine

to do all that, by one simple line:

$output = json_encode(array_combine($format, $entries));

That’s all of it! Faster, reliable and clean-looking code.

Advertisements

2 thoughts on “Creating nice JSON strings on PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s