通过php中的多维数组循环

时间:2017-03-06 19:12:14

标签: php arrays json

最初,我使用后端即服务(Baas)通过REST API调用收集并简单地在网页上显示数据。数据采用JSON格式并解码为一维数组。我使用下面的代码成功遍历数组并显示'文本'数组中的值在网页上一次一行:

$returned_content = get_data('https://api.backendless.com/v1/data/Alerts');     //returns JSON

$data = json_decode($returned_content); //JSON to array

foreach ($data->results as $item) {

    echo '<p>'.$item->text;
}

我切换了BaaS提供商,现在解码时的JSON是多维数组。输出的摘录如下:

&#13;
&#13;
array (
  'offset' => 0,
  'data' => 
  array (
    0 => 
    array (
      'created' => 1486047487000,
      '___class' => 'Alerts',
      'text' => 'Thank you for attending the 2017 BICSI Winter Conference and Exhibition in Tampa, FL.',
      'ownerId' => NULL,
      'updated' => NULL,
      'objectId' => '610DF2CC-B333-4BAA-FF93-224B8273B100',
      '__meta' => '{"relationRemovalIds":{},"selectedProperties":["created","___class","text","ownerId","updated","objectId"],"relatedObjects":{}}',
    ),
    1 => 
    array (
      'created' => 1486047378000,
      '___class' => 'Alerts',
      'text' => 'Thank you for attending the 2017 BICSI Winter Conference and Exhibition in Tampa, FL.',
      'ownerId' => NULL,
      'updated' => NULL,
      'objectId' => '43B5620F-2A19-5575-FF9F-B952AB2F0A00',
      '__meta' => '{"relationRemovalIds":{},"selectedProperties":["created","___class","text","ownerId","updated","objectId"],"relatedObjects":{}}',
    ),
    2 => 
    array (
      'created' => 1476139578000,
      '___class' => 'Alerts',
      'text' => 'test5 pw and backendless',
      'ownerId' => NULL,
      'updated' => NULL,
      'objectId' => '97B1BC3A-3233-2265-FF73-752BA720F300',
      '__meta' => '{"relationRemovalIds":{},"selectedProperties":["created","___class","text","ownerId","updated","objectId"],"relatedObjects":{}}',
    ),
  ),
	  'nextPage' => 'https://api.backendless.com/v1/data/Alerts?pageSize=10&offset=10',
	  'totalObjects' => 44,
)
&#13;
&#13;
&#13;

我不是PHP的专家,我无法弄清楚如何遍历这个多维数组并简单地显示&#39;文本&#39;像我一维数组那样的值。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

非常相似:

foreach ($data['data'] as $item) {

    echo '<p>'.$item['text'];
}
  1. 符号不同,使用$array['key']代替$object->key

  2. $data->results中的任何内容现在都在$data['data']

  3. 那应该是它。

    我可以调用json_decode(json_encode($dataArray))来获取数组的stdClass项目表示。有时使用->表示法更容易。

    刚刚注意到你有点混淆,数组和对象术语。我认为新的BaaS只是使用不同的密钥来存储实际数据。试试这个:

    $returned_content = get_data('https://api.backendless.com/v1/data/Alerts');     //returns JSON
    
    $data = json_decode($returned_content['data']); //JSON to array
    
    foreach ($data as $item) {
    
        echo '<p>'.$item->text;
    }