【问题标题】:php get json string key and value [duplicate]php获取json字符串键和值[重复]
【发布时间】:2015-06-30 06:21:58
【问题描述】:

在 php 中如何获取 activity_id_0 和 student_phone_0 的值等等。 我的 json 字符串就像

array(
    'json_text' => '{
    "student_activity":{"activity_id_0":"1","student_id_0":"1","charges_0":"123"},
    "student_contact_info":{"student_phone_0":"7867857986","student_id_0":"1","student_email_0":""}
    }'
)

【问题讨论】:

  • 你有没有试过???
  • 我试过 json_decode 但它给了我错误

标签: php json


【解决方案1】:

您可以将此json解码为数组并通过键获取:

$a = array(
    'json_text' => '{
    "student_activity":{"activity_id_0":"1","student_id_0":"1","charges_0":"123"},
    "student_contact_info":{"student_phone_0":"7867857986","student_id_0":"1","student_email_0":""}
    }'
);
$json = json_decode($a['json_text'],true);
$activity_id_0 = $json["student_activity"]["activity_id_0"];
$student_phone_0 = $json["student_contact_info"]["student_phone_0"];
echo $activity_id_0,' ',$student_phone_0; //1 7867857986 

【讨论】:

    【解决方案2】:

    使用json_decode():

    $arr = array(
        'json_text' => '{
            "student_activity":{"activity_id_0":"1","student_id_0":"1","charges_0":"123"},
            "student_contact_info":{"student_phone_0":"7867857986","student_id_0":"1","student_email_0":""}
        }'
    );
    
    var_dump(json_decode($arr['json_text'])->student_contact_info->student_phone_0);
    

    PHP 手册中的更多信息:http://php.net/manual/en/function.json-decode.php

    【讨论】:

      【解决方案3】:

      这里需要将json对象转成数组,试试下面的代码

      $info = array(
              'json_text' => '{
              "student_activity":{"activity_id_0":"1","student_id_0":"1","charges_0":"123"},
              "student_contact_info":{"student_phone_0":"7867857986","student_id_0":"1","student_email_0":""}
              }'
          );
      
          // here we can convert json object into an array
          $arrayInfo = json_decode($info['json_text'], true);
      
          echo '<pre>';
          print_r($arrayInfo['student_activity']);
          print_r($arrayInfo['student_contact_info']);
      

      我认为它会对你有所帮助.. :-)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-08
        • 2019-05-12
        • 2018-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-11
        相关资源
        最近更新 更多