【问题标题】:How to convert json to php array and use foreach on it?如何将 json 转换为 php 数组并在其上使用 foreach?
【发布时间】:2016-02-20 09:18:13
【问题描述】:

我已经构建了一个 Telegram 机器人,并希望回复发送给我的机器人的任何消息。我使用了 getUpdates 方法并收到了一个 JSON 对象。现在我想从中提取任何 chat_id 并使用 sendMessage 方法向它发送消息。 请帮助我如何为此使用foreach。 以下是我的 JSON 对象:

{"ok":true,"result":[{"update_id":709393586, "message":{"message_id":60,"from":{"id":123456789,"first_name":"Ameer","last_name":"Mousavi","username":"ameer_mousavi"},"chat":{"id":123456789,"first_name":"Ameer","last_name":"Mousavi","username":"ameer_mousavi"},"date":1436038917,"text":"hi"}}]}'

对不起,初学者的问题;)我对编程很陌生。

【问题讨论】:

  • @VolkerK 我看到了,但我不知道 :(
  • 您发布的 JSON 文字(sn-p?)中没有任何内容适合 foreach,imo。 result 是一个数组,因此它可以与 foreach 一起使用。但在给定的示例中,它仅包含一个元素 ....
  • 谢谢@VolkerK!我找到了;)

标签: php json telegram-bot


【解决方案1】:

我找到了解决方案。代码如下:

`$obj = json_decode($result, true);
foreach ($obj["result"] as $key => $value) {
    $temp_chat_id =  $value["message"]["chat"]["id"];
    sendMessage($temp_chat_id, "Hi");
}`

【讨论】:

【解决方案2】:
<?php
$response = json_decode(data(), true);
if ( !$response['ok'] ) {
    die('not ok');
}
else {
    foreach($response['result'] as $result) {
        echo $result['update_id'], ' ', $result['message']['chat']['id'], "\r\n";
    }
}


function data() {
    return '{"ok":true,"result":[{"update_id":709393586,
"message":{"message_id":60,"from":{"id":123456789,"first_name":"Ameer","last_name":"Mousavi","username":"ameer_mousavi"},"chat":{"id":123456789,"first_name":"Ameer","last_name":"Mousavi","username":"ameer_mousavi"},"date":1436038917,"text":"hi"}}]}';
}

打印

709393586 123456789

即update_id 和聊天元素的 id。

【讨论】:

猜你喜欢
  • 2023-03-17
  • 2019-04-17
  • 2019-08-10
  • 2018-08-18
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
相关资源
最近更新 更多