【问题标题】:Problem with looping through arrays in php [duplicate]在php中循环遍历数组的问题[重复]
【发布时间】:2022-01-21 08:12:56
【问题描述】:

我希望能够导航到下表中的坐标:

{
  "type": "Polygon",
  "coordinates": [
    [
      [
        37.02255983,
        -1.43654556
      ],
      [
        37.08298464,
        -1.41777117
      ],
      [
        37.03893607,
        -1.44272341
      ],
      [
        36.96500169,
        -1.48081985
      ],
      [
        36.91303988,
        -1.47429887
      ]
    ]
  ]
}

我正在从数据库中提取这些数据,并且我的第一级循环导致上述对象数组。 我的一级代码如下:

<?php
    $locations = \App\Model::all();
    foreach ($locations as $key=>$location)
    {
      $polygonXML = $location['polygon'];
      dd($polygonXML);
    }
?>

我想以坐标键结束。

【问题讨论】:

  • 发布您当前的代码

标签: php arrays json


【解决方案1】:

你拥有的数据是JSON格式的,所以你必须先用json_decode()将它转换成PHP中的可迭代对象,这会将它转换成一个数组,然后可以使用一个简单的foreach循环去通过"coordinates" 表中的每个条目。

<?php

// Encode your JSON data from where it is coming from.
$data = json_decode('{
  "type": "Polygon",
  "coordinates": [
    [
      [
        37.02255983,
        -1.43654556
      ],
      [
        37.08298464,
        -1.41777117
      ],
      [
        37.03893607,
        -1.44272341
      ],
      [
        36.96500169,
        -1.48081985
      ],
      [
        36.91303988,
        -1.47429887
      ]
    ]
  ]
}', true);

foreach($data["coordinates"][0] as $coodinate)
{
    var_dump($coodinate[0] . ", " . $coodinate[1]);
}

输出:

string(24) "37.02255983, -1.43654556"
string(24) "37.08298464, -1.41777117"
string(24) "37.03893607, -1.44272341"
string(24) "36.96500169, -1.48081985"
string(24) "36.91303988, -1.47429887"

【讨论】:

    猜你喜欢
    • 2016-08-24
    • 2012-02-28
    • 2018-02-13
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多