-4

I have 1 table contains json data like below.

{"14":"17","17":"29","18":"74","19":["80"],"20"["82","83","84"],"21":["85","86","87"],"23":""}

I want to convert this data to variable in my php page.

As you can see, every key can be a variable,

$id_14 = 17
$id_17 = 29
$id_18 = 74
$id_19 = 80
$id_20 = 82, 83, 84
$id_21 = 85, 86, 87
$id_23 = null or empty

I am using the json_decode method but I cannot convert it exactly. Thanks in advance.

Aftab H.
  • 1,517
  • 4
  • 13
  • 25
sakirow
  • 189
  • 1
  • 5
  • 18
  • 1
    There are sooo many answers related to this question. Please do a basic Google Search – Rotimi Jan 16 '18 at 17:59
  • what array are you getting after json_decode() show us the code. – Alam Darji Jan 16 '18 at 18:05
  • Possible duplicate of [PHP - Extract JSON result from API to several PHP variables](https://stackoverflow.com/questions/48271137/php-extract-json-result-from-api-to-several-php-variables) – Philipp Maurer Jan 16 '18 at 18:13
  • 2
    Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – Peter Jan 16 '18 at 18:14
  • @PhilippMaurer. as you can see my json has different option in [ ]. if i take this parameter as key/value, i cannot handle the [ ] part. – sakirow Jan 16 '18 at 18:28

1 Answers1

0
$arr = json_decode($str, true);
// create array, referencing to variables
$vars = [14 => &$var_14,.. 20 => &$var_20,..];
foreach($vars as $k=>&$var) {
  // Get corresponding array value
  if(isset($arr[$k])) {
     if (is_array($arr[$k])) {
       $var = implode(',', $arr[$k]);
     }
     else {
       $var = $arr[$k];
    }
  }
  else {
    // if does not present in json array set default value
    $var = false;
  }
}
unset($vars);
echo $var_20; // 82,83,84
splash58
  • 26,043
  • 3
  • 22
  • 34
  • this code runs well but i need some modification. when i added all id into $vars, is_array block throws exeption, for ex: you searched $var_14, i am searching $var_14, $var_15,$var_20. my data sometimes have $var_14, sometimes has all. how can i set this $vars array dynamic? – sakirow Jan 17 '18 at 19:27
  • splash58 please help me, for ex: $vars = [14 => &$var_14, 20 => &$var_20,18 => &var_18] if there is no 18 in the json data, is_array throws exception and the result is abnormal. – sakirow Jan 17 '18 at 19:36
  • @ŞakirBostancı add one more check. I've updated the answer – splash58 Jan 17 '18 at 20:58