如何使用php读取json编码值?

时间:2018-01-11 05:29:36

标签: php json

我在PHP中有一个变量,命名为$ partialSegments。我希望在我点击operatorrOperandValue等时迭代它并执行操作。我在函数调用中收到它,因此在制作

function named(say):
 public function convertJsCode($partialSegments){
//logic
}

我正在努力解决逻辑

"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}

2 个答案:

答案 0 :(得分:2)

在php

中使用json_decode()函数
  <?php

$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';

$parsed = json_decode($json, true);

foreach($parsed["segments"]["partialSegments"] as $val) {


    $operator = $val["operator"]; // operator value 
    $rOperandValue = $val["rOperandValue"][0]; // rOperandValue value 

}

?>

答案 1 :(得分:0)

Step1:使用json_decode();函数将json编码数据转换为php数组。该函数接收两个参数:第一个是:json_encoded数据应该被解码,第二个是:boolean(TRUE or FALSE)。将第二个参数传递为TRUE将json的编码值转换为php数组,如果传递false则会返回php对象。

Step2:迭代php数组并将逻辑设置为魅力。

<?php

$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';

$parsed = json_decode($json, true);

foreach($parsed as $single){
  $segments = $single['partialSegments'];
  //print_r($single);

  foreach($segments as $segment){
      echo 'operator:'. $segment['operator'].'<br>';
            print_r($segment['rOperandValue']);
      // put your logic based on 'operator' or 'rOperandValue'
    }

}

?>

建议:不要使用硬代码索引来处理类似:$segment['rOperandValue'][0]的数组。数组可能是空的。即:如果你想在$segment['rOperandValue'] use in_array()找到值时做任何事情。