Created
August 9, 2018 20:39
-
-
Save wallacemaxters/8ad0e55571c3182cdee5090b97dc2d9e to your computer and use it in GitHub Desktop.
json_encode implementation with callback, like JSON.stringify of the Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Wallace Maxters <[email protected]> | |
* 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tests:
the result is: