将 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 代码来分隔记录。

I am unsure how to go about being able to convert the data to JSON so I can use foreach code to separate the records.

我认为这里有一个相当严重的误解。如果你想 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.