【问题标题】:handle multiple multidimensional arrays and return as json string处理多个多维数组并以 json 字符串形式返回
【发布时间】:2015-12-20 00:29:03
【问题描述】:

我正在连接到 API,我正在使用 Guzzle/pool 通过多个 GET 请求从中检索 多个 JSON 字符串

Json 字符串如下所示:

{
  "channel":
  {
    "id": 9,
    "name": "my_house",
    "description": "Netduino Plus connected to sensors around the house",
    "latitude": "40.44",
    "longitude": "-79.996",
    "field1": "Light",
    "field2": "Outside Temperature",
    "created_at": "2010-12-13T20:20:06-05:00",
    "updated_at": "2014-02-26T12:43:04-05:00",
    "last_entry_id": 6060625
  },
  "feeds":
  [
    {
      "created_at": "2014-02-26T12:42:49-05:00",
      "entry_id": 6060624,
      "field1": "188",
      "field2": "25.902335456475583"
    },
    {
      "created_at": "2014-02-26T12:43:04-05:00",
      "entry_id": 6060625,
      "field1": "164",
      "field2": "25.222929936305732"
    }
  ]
}

然后我解析它并得到维度数组。

//变量 $response 存储所有这些 JSON 字符串。

$decode=json_decode($response,true).

//$decode存储所有多维数组

如果我使用print_r($decode),我会得到所有这些数组。 这是很多代码。我把它放在那里http://pastebin.com/N7zeRgBv

这个带有 feeds 键的内部数组可以包含不同数量的下一个内部数组。

问题也是多维数组和内部数组的key是一样的。正如您在 pastebin 文件中看到的那样,只有值是其他值。这就是我很难用这个数组操作的方式。

如何在php中处理这个多维数组?不知何故,我需要以 json 格式发送我的 ajax 响应。有什么办法吗?

【问题讨论】:

    标签: php ajax api laravel guzzle


    【解决方案1】:

    我不完全确定你在问什么,但 json 是一个多维数组,你只是将它解码成一个 php 数组。你只想要数组中的一些值吗?如果是这种情况,您可以使用 foreach 之类的方式遍历数组

    foreach($decode as $decod) {
        $whatImLookingFor = $decod['field1'];
    }
    

    【讨论】:

    • 另外查看您发布的数组,它是三个不同的数组。您可能打印了 3 次相同的数组。
    【解决方案2】:

    在 Guzzle 中发送 JSON 相当容易。事实上,这很容易,甚至还有一个专门针对它的request option

    // request($method, $uri, $options) proxies to requestAsync($method, $uri, $options)
    // and sets the $options[RequestOptions::SYNCHRONOUS] to true
    // and then waits for promises to resolve returning a Psr7\http-message\ResponseInterface instance
    $response = $client->request($method, $uri, [
        'json'  => $multi_dimensional_array,
    ]);
    

    如果内容已经是 json 编码,您只需将其添加为请求的正文,并根据服务器的配置设置 Content-Type 标头。比如:

    $response = $client->request($method, $uri, [
        'headers'   => [
            'Content-Type' = 'application/json',
        ],
        'body'      => GuzzleHttp\Psr7\stream_for($content),
    ]);
    

    【讨论】:

    • 响应已经是json字符串了..我得到了多个json字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 2020-07-30
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多