clqms-be/app/Helpers/json_helper.php

48 lines
1.5 KiB
PHP
Raw Normal View History

<?php
if (!function_exists('convert_empty_strings_to_null')) {
/**
* Recursively convert empty strings to null in arrays or objects
*
* @param mixed $data The data to process (array, object, or scalar)
* @return mixed The processed data with empty strings converted to null
*/
function convert_empty_strings_to_null($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
if (is_array($value)) {
$data[$key] = convert_empty_strings_to_null($value);
} elseif (is_object($value)) {
$data[$key] = convert_empty_strings_to_null($value);
} elseif ($value === '') {
$data[$key] = null;
}
}
} elseif (is_object($data)) {
foreach ($data as $key => $value) {
if (is_array($value)) {
$data->$key = convert_empty_strings_to_null($value);
} elseif (is_object($value)) {
$data->$key = convert_empty_strings_to_null($value);
} elseif ($value === '') {
$data->$key = null;
}
}
}
return $data;
}
}
if (!function_exists('prepare_json_response')) {
/**
* Prepare data for JSON response by converting empty strings to null
* This is a convenience wrapper around convert_empty_strings_to_null
*
* @param mixed $data The data to prepare for JSON response
* @return mixed The processed data ready for JSON encoding
*/
function prepare_json_response($data) {
return convert_empty_strings_to_null($data);
}
}