Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@wallacemaxters wallacemaxters commented Aug 9, 2018

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