以自定义格式检索JSON值

时间:2017-10-30 10:29:39

标签: php json

我有这种格式的JSON

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

我想以这种方式检索数据

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

我需要做什么?

4 个答案:

答案 0 :(得分:1)

要在单独的变量中获取每个值,都不是您想要的。

所以把它放在一个数组中。我猜您希望能够通过属性访问该值,这就是为什么我格式化输出数组。

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

打印:

Array
(
    [A] => 1
    [B] => 1
    [C] => 0
)

答案 1 :(得分: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);

答案 2 :(得分:0)

使用json_decode将json转换为数组。

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

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

输出

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

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

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

)

答案 3 :(得分:0)

检查以下代码:

<?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);
?>

输出:

数组([ValueOfA] =&gt; 1 [ValueOfB] =&gt; 1 [ValueOfC] =&gt; 0)