public function __construct(array $array)
{
$this->data = $this->initTypes($array);
}
private function getType($value)
{
switch (true) {
case (is_numeric($value)):
return is_float($value) ? (float) $value : (int) $value;
case (is_bool($value) || $value === 'false' || $value === 'true'):
return (bool) $value;
break;
case (is_array($value)):
return (array) $value;
break;
default:
return (string) $value;
}
}
private function initTypes(array $data): array
{
return array_map([$this, 'getType'], $data);
}
$testArray = [
'array' => [1,2,3, 'test'],
'bool' => false,
'bool2' => 'true',
'int' => time(),
'int2' => '2',
'float' => microtime(true),
'float2' => "2.3"
];
$jsonString = json_encode($testArray, JSON_THROW_ON_ERROR);
$json = new MyJson(json_decode($jsonString, true, 512, JSON_THROW_ON_ERROR));
echo '<pre>';
var_dump($json);
object(MyJson)#1 (1) {
["data":"MyJson":private]=>
array(7) {
["array"]=>
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
string(4) "test"
}
["bool"]=>
bool(false)
["bool2"]=>
bool(true)
["int"]=>
int(1667929711)
["int2"]=>
int(2)
["float"]=>
float(1667929711.202979)
["float2"]=>
int(2)
}
}