简体   繁体   English

如何从PHP中的嵌套json获取值

[英]How to get a value from nested json in php

I am a beginner to JSON and i'm trying to get values from a json string. 我是JSON的初学者,我正尝试从json字符串获取值。 For example i want to read the first "t":1443502800 and assing it to a variable $beginTime and the second "t":1443790800 assigned to a variable $endTime 例如,我想读取第一个“ t”:1443502800并将其分配给变量$ beginTime ,将第二个“ t”:1443790800分配给变量$ endTime

{
  "op":"&",
  "c":[
       {
         "type":"date",
         "d":">=",
         "t":1443502800
       },
       {
         "type":"date",
         "d":"<",
         "t":1443790800
       }
     ],
  "showc":[true,true]
}

I would really appreciate any help :) 我真的很感谢您的帮助:)

Edit code 编辑代码

foreach($rs2 as $record2)
    { 
      if( $record2->availability == '{"op":"&","c":[],"showc":[]}'){
        //skip, because the restriction date was not set for this attendance
      }
      else{
        //get the restriction date by making use of json                  
         $json_data = json_decode($record2->availability, true);
         echo $json_data['c'];
      }
    } 

The problem is you can't echo an array. 问题是您无法回显数组。 You're trying to echo out $json_data['c'] , which is an array. 您正在尝试回显$json_data['c'] (它是一个数组)。 Either return it or echo out what you need. 退还它或回显您的需求。 For instance to echo out the start time use echo $json_data['c'][0]['t'] 例如,要回显开始时间,请使用echo $json_data['c'][0]['t']

ORIGINAL ANSWER 原始答案

You should use json_decode without true in the second variable. 您应该在第二个变量中使用不带true的json_decode。 Then you have objects (started with braces { ) and arrays (started with square brackets [ ). 然后,您有对象(以大括号{开头)和数组(以方括号[开头[ )。 You can then get the start and end times us 然后,您可以获取开始时间和结束时间

<?php
$string = '{
  "op":"&",
  "c":[
       {
         "type":"date",
         "d":">=",
         "t":1443502800
       },
       {
         "type":"date",
         "d":"<",
         "t":1443790800
       }
     ],
  "showc":[true,true]
}';
$json = json_decode($string);
echo "Start time: ".$json->c[0]->t;
echo "End time: ".$json->c[1]->t;

Here's an eval.in of it working - https://eval.in/441599 下面是它的工作的eval.in - https://eval.in/441599

You were almost there. 你快到了 The full call should be to 完整的通话应该是

$beginTime = $json_data['c'][0]['t'];

since $json_data['c'][0] is the array: 因为$json_data['c'][0]是数组:

array (
    "type" => "date",
    "d" => ">=",
    "t" => 1443502800
),

The $endtime can be obtained in a similar manner: $endtime可以通过类似的方式获得:

$endTime = $json_data['c'][1]['t'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM