简体   繁体   中英

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. I used getUpdates method and received a JSON object. Now I want to extract any chat_id from this and send a message to it using sendMessage method. Please help me how to use a foreach for this. The below is my JSON object:

{"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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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