【问题标题】:How to manipulate JSON in php?如何在 php 中操作 JSON?
【发布时间】:2017-08-07 16:40:45
【问题描述】:

假设我有一个如下所示的 JSON 对象:

{"tag":[{"Item1":"Required"},{"Item2":"Not Required"},{"Item3":"Maybe Required"}]}

我将这个从 volley 发布到接收 JSON 对象的服务器,如下所示:

 $json = file_get_contents('php://input');

假设我想检查是否收到了 item2?我该怎么做?

我试过了:

<?php

$json = file_get_contents('php://input');// Assuming $json looks like: {"tag":[{"Item1":"Required"},{"Item2":"Not Required"},{"Item3":"Maybe Required"}]}

$temp=$json["tag"];// assuming $temp would look like: [{"Item1":"Required"},{"Item2":"Not Required"},{"Item3":"Maybe Required"}]

$temp1=$temp[1]["Item2"];//assuming $temp1 looks like: "Not Required"

$data=array();

$temp2=array('Status'=>$temp1);// assuming $temp2 looks like ["Status"=>"Not Required"]
array_push($data,$temp2);

$response=array('phpStatus'=>$data);// assuming $response looks like: ["phpStatus"=>["Status"=>"Not Required"]]

echo json_encode($response);// Assuming encoded version should look like: {"phpStatus":[{"Status":"Not Required"}]}

?>

注意:假定的编码 json 正是我想在 android 中接收的!

{"phpStatus":[{"Status":"Not Required"}]}

【问题讨论】:

  • 如果你想使用它,你需要打电话给json_decode,否则你就在正确的轨道上
  • @iainn 我不能直接操作收到的 JSON 吗?
  • 不,它只是一个字符串,直到你解码它。 file_get_contents 将从请求中检索一个字符串,然后调用json_decode 将该字符串转换为 PHP 数据结构。见php.net/manual/en/function.json-decode.php
  • @iainn 当然我正在尝试!

标签: php android json android-volley


【解决方案1】:

当你用file_get_contents拉取JSON时,它只是一个字符串,所以你需要json_decode这个JSON字符串来访问值。

当您解码字符串时,您的 JSON 数据现在是一个数组,如下所示:

Array
(
    [tag] => Array
        (
            [0] => Array
                (
                    [Item1] => Required
                )

            [1] => Array
                (
                    [Item2] => Not Required
                )

            [2] => Array
                (
                    [Item3] => Maybe Required
                )
        )
)

这是一个简短的工作 sn-p:

 $json_in = '{"tag":[{"Item1":"Required"},{"Item2":"Not Required"},{"Item3":"Maybe Required"}]}';

 // Decodes JSON into an associative array.
 $JSON = json_decode($json_in, true);

 // Displays data neatly for you to see the structure of the array.
 echo "<pre>";
 print_r($JSON);

 // Retreive Item2
 $item2 = $JSON['tag'][1]['Item2'];

 if ($item2 === "Required")
     {
     echo "is received";
     } else
     {
     echo 'is not received';
     }

【讨论】:

  • @VidorVistrom 没问题,很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
相关资源
最近更新 更多