Skip to content

Instantly share code, notes, and snippets.

@wallacemaxters
Created August 9, 2018 20:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save wallacemaxters/8ad0e55571c3182cdee5090b97dc2d9e to your computer and use it in GitHub Desktop.
json_encode implementation with callback, like JSON.stringify of the Javascript
<?php
/**
* @author Wallace Maxters <wallacemaxters@gmail.com>
* Encodes json after apply callback in data passed
*
* @param mixed $data
* @param callable $callback
* @param int $options
* @return string
*/
function json_encode_callback($data, callable $callback, $options = 0)
{
$isIterable = static function ($data) {
return is_array($data) || $data instanceof \stdClass || $data instanceof Iterator;
};
$recursiveCallbackApply = static function ($data, callable $callback) use(&$recursiveCallbackApply, $isIterable) {
if (! $isIterable($data))
{
return $callback($data);
}
foreach ($data as $key => &$value) {
if ($isIterable($value)) {
$value = $recursiveCallbackApply($value, $callback);
continue;
}
$value = $callback($value, $key);
}
return $data;
};
return json_encode($recursiveCallbackApply($data, $callback), $options);
}
@wallacemaxters
Copy link
Author

Tests:

$obj = new stdClass;

$obj->date = new DateTime;

$obj->name = "Wallace";

$result = json_encode_callback($obj, function ($value) {
    return $value instanceof \DateTime ? $value->format('c') : $value;
});

var_dump($result);

the result is:

string(53) "{"date":"2018-08-09T17:41:27-03:00","name":"Wallace"}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment