php mysql point類型進行轉換

最近項目中用到地理坐標,所以mysql就使用了point類型,當然查詢的時候可以用mysql的空間函數實現,ST_X(p):獲取點 p 的 X 坐標,ST_Y(p):獲取點 p 的 Y 坐標。

但我覺得還是用php實現好點,讓它自動轉換,因為我用的thinkphp,在 ThinkPHP 框架中,get+字段名+Attr 是一種用於定義模型屬性訪問器(Accessor)的方法。屬性訪問器允許你在獲取模型屬性時對數據進行自定義處理。這種機制通常用于格式化數據、轉換數據類型或進行其他數據處理操作。

我的location字段保存了地理坐標,所以我在模型層定義了一個getLocationAttr方法,讓它自動轉換,實現方法如下,希望有相同需求的人可以用上

    public function getLocationAttr($point): array
    {
        $offset = 4;  // 跳過前 4 個字節
        $byteOrder = ord($point[$offset]);
        $srid = unpack($byteOrder === 1 ? 'V' : 'N', substr($point, $offset + 1, 4))[1]; // 使用 'V' 解包小端序,'N' 解包大端序
        if ($srid !== 1) { // 1 表示 Point 類型
            return [
                'longitude' => null,
                'latitude' => null
            ];
        }
        $offset += 5; // 1 字節字節序 + 4 字節幾何類型
        if ($byteOrder === 1) {
            $x = unpack('d', substr($point, $offset, 8))[1];
            $y = unpack('d', substr($point, $offset + 8, 8))[1];
        } else { // 大端序
            $x = unpack('d', strrev(substr($point, $offset, 8)))[1];
            $y = unpack('d', strrev(substr($point, $offset + 8, 8)))[1];
        }
        return [
            'longitude' => $x,
            'latitude' => $y,
        ];
    }


查詢出來location自動轉換