简体   繁体   English

如何将json转换为php数组并使用foreach呢?

[英]How to convert json to php array and use foreach on it?

I've build a Telegram bot and want to replying any message that is sending to my bot. 我已经构建了一个Telegram机器人,并希望回复发送到我的机器人的任何消息。 I used getUpdates method and received a JSON object. 我使用了getUpdates方法并收到了一个JSON对象。 Now I want to extract any chat_id from this and send a message to it using sendMessage method. 现在我想从中提取任何chat_id并使用sendMessage方法向它发送消息。 Please help me how to use a foreach for this. 请帮助我如何使用foreach。 The below is my JSON object: 以下是我的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"}}]}'

Sorry for beginner question ;) I'm fairly new to programming. 对不起初学者的问题;)我对编程很新。

I found the solution. 我找到了解决方案。 Here is the code: 这是代码:

`$obj = json_decode($result, true);
foreach ($obj["result"] as $key => $value) {
    $temp_chat_id =  $value["message"]["chat"]["id"];
    sendMessage($temp_chat_id, "Hi");
}`
<?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"}}]}';
}

prints 版画

709393586 123456789

ie the update_id and the id of the chat element. 即update_id和聊天元素的id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM