簡體   English   中英

將PHP var_dump數組轉換為JSON

[英]Converting PHP var_dump array to JSON

一直在尋找解決方案。 找不到一個,所以我的最后選擇當然是在這里。

我正在使用MessageBird的API。 該代碼的目的是吐出一條消息列表。

我的代碼:

require_once(__DIR__ . '/messagebird/vendor/autoload.php');
$MessageBird = new \MessageBird\Client('XXXXX'); // Set your own API access key here.
try {
$MessageList = $MessageBird->messages->getList(array ('offset' => 0, 'limit' => 30));
  //var_dump($MessageList);

} catch (\MessageBird\Exceptions\AuthenticateException $e) {
// That means that your accessKey is unknown
  echo 'wrong login';
} catch (\Exception $e) {
  var_dump($e->getMessage());
}

$json = json_decode($MessageList, true);

foreach($json as $item) {
  echo $item['body'];
}

這是數據“ var_dump”的輸出:

object(MessageBird\Objects\BaseList)#147 (6) {
  ["limit"]=>
  int(30)
  ["offset"]=>
  int(0)
  ["count"]=>
    int(24)
  ["totalCount"]=>
  int(24)
  ["links"]=>
  object(stdClass)#48 (4) {
    ["first"]=>
    string(56) "https://rest.messagebird.com/messages/?offset=0&limit=30"
    ["previous"]=>
    NULL
    ["next"]=>
    NULL
    ["last"]=>
    string(56) "https://rest.messagebird.com/messages/?offset=0&limit=30"
  }
  ["items"]=>
  array(24) {
    [0]=>
    object(MessageBird\Objects\Message)#148 (16) {
      ["id":protected]=>
      string(32) "XXX"
      ["href":protected]=>
      string(70) 
"https://rest.messagebird.com/messages/XXX"
      ["direction"]=>
      string(2) "mt"
      ["type"]=>
      string(3) "sms"
      ["originator"]=>
      string(5) "Test Sender"
      ["body"]=>
      string(416) "Hey Blah Blah Test Message."
      ["reference"]=>

我不確定如何將數據轉換為JSON,所以我可以使用foreach代碼來分隔記錄。

我不確定如何將數據轉換為JSON,所以我可以使用foreach代碼來分隔記錄。

我認為這里存在相當嚴重的誤解。 如果要foreach某些數據,則不需要var_dump JSON,更不用說兩者了-您只需要數據即可。

var_dump是一個在調試期間向程序員顯示結構的函數; 它不是可逆的,也不是在生產代碼中使用過的。

JSON是一種序列化格式,用於將數據表示為文本,因此您可以將其從一個程序傳輸到另一個程序。 您不會在任何地方傳輸對象,因此不需要JSON。

您想要的是:

try
{
    $MessageList = $MessageBird->messages->getList(array ('offset' => 0, 'limit' => 30));
    foreach($MessageList->items as $item) {
      echo $item->body;
    }
}
// Your exception handling here - note that you can't do anything with `$MessageList` if an exception happened; it won't exist.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM