Skip to content

Instantly share code, notes, and snippets.

@alexandreelise
Last active October 8, 2024 00:32
Show Gist options
  • Save alexandreelise/f572be613bf745bf92d143c6815da92f to your computer and use it in GitHub Desktop.
Save alexandreelise/f572be613bf745bf92d143c6815da92f to your computer and use it in GitHub Desktop.
generate random json data structure using a cryptographically secure prng
<?php
declare(strict_types=1);
// final associative array to json_encode
$output = [];
// root level array keys
$keys_0_min = 1;
$keys_0_max = 10;
$keys_0 = [];
for($i = 0, $i_max = random_int($keys_0_min, $keys_0_max); $i < $i_max; $i++) {
$keys_0[] = bin2hex(random_bytes(random_int(2,8)));
}
foreach ($keys_0 as $key_0)
{
if (!array_key_exists($key_0, $output))
{
$output[$key_0] = [];
// nested data
$deeper_key_min = 1;
$deeper_key_max = 10;
$deeper_value_min = 1;
$deeper_value_max = 10;
for ($n = 0, $n_max = random_int($deeper_key_min, $deeper_key_max); $n < $n_max; $n++) {
if (random_int(0, 80) > random_int(10, 40)) {
$deep_filler = [];
for($j = 0, $j_max = random_int($deeper_value_min, $deeper_value_max); $j < $j_max; $j++) {
$deep_filler[] = bin2hex(random_bytes(random_int(2,16)));
}
} else {
$deep_filler = bin2hex(random_bytes(random_int(2,16)));
}
$output[$key_0][bin2hex(random_bytes(random_int(2,4)))] = $deep_filler;
}
}
}
echo var_export($output);
@alexandreelise
Copy link
Author

Changed licence of this gist and my latest domain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment