需求
PHP实现像golang一样数组转字节,传递给go服务
go
package main
import (
"encoding/json"
"fmt"
)
type Info struct {
Id int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
}
func main() {
info := Info{
Id: 1002,
Title: "标题",
Content: "内容",
}
data, err := json.Marshal(info)
if err != nil {
fmt.Println("err = ", err.Error())
return
}
fmt.Println("data = ", data)
fmt.Println("len = ",len(data))
}
data = [123 34 105 100 34 58 49 48 48 50 44 34 116 105 116 108 101 34 58 34 230 160 135 233 162 152 34 44 34 99 111 110 116 101 110 116 34 58 34 229 134 133 229 174 185 34 125]
len = 47
PHP
<?php
class Info
{
public $id;
public $title;
public $content;
}
$info = [
'id' => 1002,
'title' => '标题',
'content' => '内容',
];
$data = unpack("C*", json_encode($info, JSON_UNESCAPED_UNICODE));
echo "[" . implode(" ", $data) . "]\n";
var_dump(count($data));
[123 34 105 100 34 58 49 48 48 50 44 34 116 105 116 108 101 34 58 34 230 160 135 233 162 152 34 44 34 99 111 110 116 101 110 116 34 58 34 229 134 133 229 174 185 34 125]
int(47)
关键函数
- json_encode Unicode原义
- unpack(“C*”,$string)
PHP unpack的参数,官方文档 https://www.php.net/manual/zh/function.pack.php
|