-1

I have a JSON in this format

    [
      {
      "Property": "A",
       "Value": "1"
      },
     {
     "Property": "B",
       "Value": "1"
      },
      {
       "Property": "C",
       "Value": "0"
     },
   ]

I want to retrieve the data in this way

    $ValueOfA = 1;
    $valueOfB = 1;
    $valueOfC = 0;

What do I need to do?

Bharat Paudyal
  • 124
  • 1
  • 10
  • 2
    Possible duplicate of [How to read JSON array using PHP?](https://stackoverflow.com/questions/39849320/how-to-read-json-array-using-php) – Alessandro Da Rugna Oct 30 '17 at 10:30
  • Just to note, you've got a syntax error here (other people seem to have noticed in their answers but not mentioned it). JSON arrays shouldn't have a comma after the last element, which will be causing problems with `json_decode` – iainn Oct 30 '17 at 10:49

4 Answers4

1

To get each value in a separate variable is not what you should want.

So place it in an array. I am guessing you want to be able to access the value via the property, that's why I formatted the output array.

$array = json_decode($json, true);
$formattedArray = array();
foreach($array as $element) {
    $formattedArray[$element['Property']] = $element['Value'];
}

This prints:

Array
(
    [A] => 1
    [B] => 1
    [C] => 0
)
Pascal
  • 413
  • 3
  • 13
0

e.x

$json = '[
    {
        "Property":"A",
        "Value":"1"
    },
    {
        "Property":"B",
        "Value":"1"
    },
    {
        "Property":"C",
        "Value":"0"
    }
]';

$json_converted = json_decode($json, true);

$temp = "";
foreach($json_converted as $value){
    $temp = "valueOf".$value["Property"];
    $$temp = $value['Value'];

}

var_dump($valueOfA);
var_dump($valueOfB);
var_dump($valueOfC);
long
  • 86
  • 5
0

Use json_decode to convert the json into an array.

$json = '[
    {
        "Property":"A",
        "Value":"1"
    },
    {
        "Property":"B",
        "Value":"1"
    },
    {
        "Property":"C",
        "Value":"0"
    }
]';

$json_converted = json_decode($json, true);
print_r($json_converted);

The output will be

Array
(
    [0] => Array
        (
            [Property] => A
            [Value] => 1
        )

    [1] => Array
        (
            [Property] => B
            [Value] => 1
        )

    [2] => Array
        (
            [Property] => C
            [Value] => 0
        )

)
Mad Angle
  • 2,347
  • 1
  • 15
  • 33
0

Check below code:

<?php
    $jsonData = '[{
          "Property": "A",
           "Value": "1"
          },
         {
         "Property": "B",
           "Value": "1"
          },
          {
           "Property": "C",
           "Value": "0"
         }]';

    $arr = json_decode($jsonData, true);

    foreach ($arr as $key => $value) {
        $returnData['ValueOf'.$value['Property']] = $value["Value"];
    }

    print_r($returnData);
?>

Output :

Array ( [ValueOfA] => 1 [ValueOfB] => 1 [ValueOfC] => 0 )

Sadhu
  • 850
  • 2
  • 9
  • 18