up one level
Challenge - How to Serialize a String to JSON in PHP
In the context of web development, I was recently challenged to:
Below is a description of one way to complete the challenge.
I completed the challenge, at the same time as learning a bit about web development and learning a bit about array serialization to JSON in PHP.
An internet search, on how to serialize a string in PHP, yielded this article: ( http://stackoverflow.com/questions/...-unserialize ). Reading it taught me some about the why and how of serialization in PHP.
Reviewing the challenge question. It was a bit open-ended, and requested to serialize the string.
To make it more clear that I had serialized the string, I decided it would be better to first split it into characters, then encode it in JSON, then echo the string back out to the screen as json-formatted text.
Well, if I just serialized the string, like:
, then there would be no output; the string would just be serialized in memory on the server.
So I thought I would echo it out on the screen via the browser window:
I think this is a bit better.
Hm, but now It seems unclear that it was serialized, and also it doesn't look like JSON format either -- there's little proof that I did any work. I feel I need to show my work a bit more, via the results. What if I split the string first, into an array, by using the PHP str_split() function?
That's better, but it still doesn't look like JSON data. I look in the PHP manual for ideas: ( http://php.net/manual/en/function.json-encode.php ). I find the JSON_FORCE_OBJECT option, and use it:
echo json_encode(str_split('PHP'), JSON_FORCE_OBJECT);
That's better -- challenge done -- Ship it! (à la http://scotchisforshippers.com/ )
This has been a description of one way to complete the coding challenge, at the same time as learning a bit about web development and learning a bit about array serialization to JSON in PHP.
Note: This post was pre-published on November 18, 2016.
[2019 edit: Moved to: https://investorworker.com/2016/... .html.]