I am verifying certain codes that work well and I don't know what else to optimize in them or what other tests to do: in this case it is a php script that takes the data of the $_POST
variable analyzes them and converts them into an array, this is since in some cases the post field may contain a JSon
string.
I leave a functional example where I have manually set the $_POST
variable to do the Demonstration:
https://wtools.io/php-sandbox/bqsT
Original Code example:
<?php
#Example Array
$_POST = array(
"valor1" => 1200,
"valor2" => "texto",
"valor3" => true,
"valor4" => '{"seclvl_text":"datp","seclvl_boolean":"false"}',
);
#Validate Function for Json
function ValidateJson($Var) {
if (!is_array($Var)) {
return ((json_decode($Var) != null) AND (is_object(json_decode($Var)) OR is_array(json_decode($Var)))) ? true : false;
} else {
return false;
}
}
#Parse Function
function buildVirtualData($data) {
if (is_array($data)) {
$result = [];
foreach ($data as $key1 => $val1) {
$valJson = ValidateJson($val1);
if ($valJson) {
$jsonObj = json_decode($val1, true);
$result[$key1] = buildVirtualData($jsonObj);
} elseif ($valJson == false && is_array($val1)) {
foreach ($val1 as $key2 => $val2) {
$result[$key1][$key2] = buildVirtualData($val2);
}
} else {
if ($val1 === 'true') {
$val1 = true;
} else if ($val1 === 'false') {
$val1 = false;
}
$result[$key1] = $val1;
}
}
return $result;
} else {
if (ValidateJson($data)) {
$jsonObj = json_decode($data, true);
return buildVirtualData($jsonObj);
} else {
return $data;
}
}
}
# call to Function:
$data = buildVirtualData($_POST);
echo '<pre>';
echo var_dump($data);
echo '</pre>';
this parse have the feature that convert any text true or false to Boolean.