Skip to content

Instantly share code, notes, and snippets.

@JeffTomlinson
Last active September 9, 2015 20:07
Show Gist options
  • Save JeffTomlinson/7d5979c16d0bfc299623 to your computer and use it in GitHub Desktop.
Save JeffTomlinson/7d5979c16d0bfc299623 to your computer and use it in GitHub Desktop.
Convert a JSON object to a string representation of a PHP array.
var _ = require('lodash');
/**
* Renders input value as a string representation of a php variable value.
*
* @param {int|boolean|string} value - The value to render.
*
* @returns {string} A string representing a php variable value.
*/
renderPhpVar = function(value) {
var rendered;
if (_.isFinite(value)) {
rendered = value;
}
else if (_.isBoolean(value)) {
rendered = value ? 'TRUE' : 'FALSE';
}
else {
rendered = "'" + value + "'";
}
return rendered;
};
/**
* Converts a json object to a string representation of a php array.
*
* @param {object} object - The json object to convert.
* @param {int} depth - Sets the initial indentation depth of the output.
* @param {array} lines - Static cache.
*
* @returns {string} A string representing a php array.
*/
jsonObjToPhpArray = function (object, depth, lines) {
if (depth == null) {
depth = 0;
}
if (lines == null) {
lines = [];
}
_.forEach(object, function(value, key) {
// If value is an object, declare value as a php array, set depth,
// and recurse.
if (_.isObject(value)) {
lines.push(_.repeat(' ', depth) + "'" + key + "' => array(");
depth++;
jsonObjToPhpArray(value, depth, lines);
depth--;
lines.push(_.repeat(' ', depth) + '),');
}
// Otherwise render as key => value.
else {
lines.push(_.repeat(' ', depth) + "'" + key + "' => " + renderPhpVar(value) + ',');
}
});
return lines.join('\n');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment