【问题标题】:How can I read a json array in PHP [duplicate]如何在 PHP 中读取 json 数组 [重复]
【发布时间】:2017-03-21 15:10:04
【问题描述】:

我有这个数组,我在 PHP 中读取(使用 curl) 它返回一个看起来像 json 的字符串,所以我将它转换为真正的 json。

但是我读它时所做的一切都行不通:

我做错了什么?如何才能达到这些价值观?

这是我得到的结果:

Array
(
    [results] => Array
        (
            [1] => Array
                (
                    [pack_id] => HUJoUJKK673ED
                    [imre] => 87687548574
                    [imrd] => 87457654764
                    [cell_id] => 775443
                    [firm_vrs] => 2
                    [gg_yr] => 2017
                    [gg_mn] => 3
                    [gg_dy] => 20
                    [gg_hr] => 15

这是我的代码

<?php
    $url = $_GET["url"];
    $curlSession = curl_init();
    curl_setopt($curlSession, CURLOPT_URL, $url);
    curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
    $returnVal = curl_exec($curlSession);
    curl_close($curlSession);

    //converting the retreived "json lookalike text" in to a json:
    $decodedText = html_entity_decode($returnVal);
    $myArray = json_decode($decodedText, true);

    //this DOES work and shows the json as an array, as described above.
    echo "<pre>";
    print_r($myArray);
    echo "</pre>";

    //BUT non of the following lines work:
    $echo = sizeof($myArray->results);
    echo "<br />".$myArray->results[1]->imre;
    echo "<br />".sizeof($myArray);
    echo "<br />".sizeof($myArray->results);
    echo "<br />".sizeof($myArray->results[1]);
    echo "<br />".sizeof($myArray[1][1]);
    echo "<br />".sizeof($myArray[0]);
    echo "<br />".sizeof($myArray[0]->results);
    echo "<br />".sizeof($myArray->imre);
    echo "<br />".sizeof($myArray[0]->results);
    echo "<br />".$myArray->results['1']->imre;
    echo "<br />".$myArray[0]->results[1]->imre;
    echo "<br />".$myArray->results[1]->imre;
    echo "<br />".sizeof($myArray->results[1]);
?>

【问题讨论】:

  • $myArray['results'][1]['pack_id']
  • 我对这个问题投了反对票,因为它真的是基本的 PHP - 如何访问数组的元素 - 并且因为你真的应该 read the manual 为你正在使用的代码,如果你没有不知道json_decode 中的true 是什么意思,这表明您在不理解代码的情况下复制和粘贴代码。
  • 解决了我的问题!谢谢!

标签: php json


【解决方案1】:

在你的线上$myArray = json_decode($decodedText, true); true 表示对象将被转换为关联数组。

但是,对于 $myArray-&gt;results 和类似的行,您会尝试像引用对象一样引用它。 请改用$myArray['results']

【讨论】:

  • 或者简单地将json解码为对象,$myArray = json_decode($decodedText);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 2019-09-20
相关资源
最近更新 更多