Skip to content

Instantly share code, notes, and snippets.

@guidoeffe
Last active September 12, 2019 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guidoeffe/2f45f4d55bd831d0fe9ec18cbe81224a to your computer and use it in GitHub Desktop.
Save guidoeffe/2f45f4d55bd831d0fe9ec18cbe81224a to your computer and use it in GitHub Desktop.
My way to create php array and variables from a json post
<?php
$post_string = file_get_contents("php://input");
if (!empty($post_string))
$post_data= json_decode($post_string, true);
}
if (isset($post_data) and is_array($post_data)){
foreach($post_data as $post_key => $post_value){
${str_name($post_key)} = $post_value;
if (is_array($post_value)){
foreach($post_value as $ex_key => $ex_value ){
${str_name($ex_key)} = $ex_value;
if(is_array($ex_value)){
foreach ($ex_value as $exx_key => $exx_value) {
${str_name($exx_key)} = $exx_value;
if(is_array($exx_value)){
foreach($exx_value as $exxx_key => $exxx_value) {
${str_name($exxx_key)} = $exxx_value;
if(is_array($exxx_value)){
foreach($exxx_value as $exxxx_key => $exxxx_value) {
${str_name($exxxx_key)} = $exxxx_value;
if(is_array($exxxx_value)){
foreach($exxxx_value as $exxxxx_key => $exxxxx_value) {
${str_name($exxxxx_key)} = $exxxxx_value;
} // foreach($exxxxx_value)
} // if(is_array($exxxxx_value))
} // foreach($exxx_value)
} // if(is_array($exxx_value))
} //foreach($exx_value)
} //if(is_array($exx_value))
} // foreach ($ex_value)
} // if(is_array($ex_value))
} // foreach($post_value)
} // if (is_array($post_value))
} // foreach ($data)
} //(is_array($post_data)
// function to normalize the name of the variable
function str_name($var_name = ''){
$name = preg_replace('/[^0-9a-zA-Z_]/', "", $var_name);
if (empty($name)){
$name = 'string_'.rand(0,9999);
}
return $name;
}
/* from here you can call a php variable or an array as you have sent as post
json post example
{
"MID": 44,
"ST": 1,
"UID": 6685059,
"MV": "1.0",
"FIFO": [{
"Date": "2019/03/20 11:40:46",
"Device": {
"Bus": 1,
"Value": 1
}
}]
}
*/
echo $MID;
echo $UID;
print_r($FIFO);
echo $Date;
print_r($Device);
echo $Bus;
echo $Value;
// etc...
// hope to be useful... ;-)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment