从坐标(php)遍历数组

时间:2011-05-15 09:59:21

标签: php multidimensional-array gis coordinates

这是我第一次参与列表,我是以下问题,我有一个动态查询,总是会返回一个包含n个元素的数组,如下例所示:

Array
(
  [0] => Array
      (
          [gid] => 311
          [length] => 408.804653251745
          [start_point] => POINT(261675 9196115)
          [end_point] => POINT(261977.5 9196357.5)
      )
  [1] => Array
      (
          [gid] => 312
          [length] => 4304.33549546129
          [start_point] => POINT(259885 9193105)
          [end_point] => POINT(261675 9196115)
      )
  [2] => Array
      (
          [gid] => 313
          [length] => 7470.68109219034
          [start_point] => POINT(262855 9190095)
          [end_point] => POINT(261675 9196115)
      )
  [3] => Array
      (
          [gid] => 314
          [length] => 1926.81240867132
          [start_point] => POINT(264465 9190755)
          [end_point] => POINT(262855 9190095)
      )
  [4] => Array
      (
          [gid] => 315
          [length] => 1828.52813742386
          [start_point] => POINT(264215 9189275)
          [end_point] => POINT(262855 9190095)
      )
)

我需要创建一个分析数组的函数,比较start_points和end_points。如果它们的元素相等,则将长度累积到一个新数组中,如下所示:

Array
(
   [0] => Array
       (
           [river_1] => "311"
           [total_length] => 408.804653251745
       )
   [1] => Array
       (
           [river_2] => "311,312"
           [total_length] => 4713.140148713
       )
   [2] => Array
       (
           [river_3] => "311,313"
           [total_length] => 7879.485745442
       )
   [3] => Array
       (
           [river_4] => "311,313,314"
           [total_length] => 9806.298154113
       )
   [4] => Array
       (
           [river_5] => "311,313,315"
           [total_length] => 9708.013882866
       )

)

我感兴趣的是长度最长的河流(river_4),请注意,从坐标通知,我可以组成5个河流。见图:https://picasaweb.google.com/benigno.marcello/Duvida?feat=directlink。阵列的河流是黄色的(在流域)。有人可以帮帮我吗?

提前致谢,

1 个答案:

答案 0 :(得分:2)

这有点脏,但这应该有效:

// Source array (this should already be set)
$river_data;

// Results array
$result_data = array();

foreach ($river_data as $river) {
    // Clear this out just in case
    $current_river = null;
    $current_river = array( 'gid' => $river['gid'],
                     'total_length' => $river['length']);

    // Compare to everything but ourselves
    foreach ($river_data as $second_river) {
        if ($river['end_point'] == $second_river['start_point']) {
            $current_river['gid'] = $current_river['gid'] . ',' . $second_river['gid'];
            $current_river['total_length'] = $current_river['total_length'] + $second_river['length'];
        }
    }

    // Add our compound river to the results array
    $result_data[] = array('river_' . (count($result_data)+1) => $result_data['gid'],
                     'total_length' => $result_data['total_length');
}