我是 go 的新手,并尝试在 go 中使用相同的值填充 slice 数据。 引用下面的例子
input struct {
ID string `json:"id"`
Name string `json:"name"`
Image string `json:"image"`
}
output struct {
ID string `json:"id"`
Name string `json:"name"`
Image []img `json:"image"`
}
img struct {
Name string `json:"name"`
Width int `json:"width"`
Height int `json:"height"`
}
input = [{
"id": 10,
"name": "product 10",
"image": {"name": "https://i.imgur.com/eKSk6Fq.jpg"}
}, {
"id": 10,
"name": "product 10",
"image": {"name": "https://i.imgur.com/np1wmxw.jpg"}
}, {
"id": 11,
"name": "product 11",
"image": {"name": "https://i.imgur.com/jlFgGpe.jpg"}
}, {
"id": 11,
"name": "product 11",
"image": {"name": "https://i.imgur.com/B0D4iRk.jpg"}
}, {
"id": 11,
"name": "product 11",
"image": {"name": "https://i.imgur.com/4AiXzf8.jpg"}
}]
// expected output
output = [{
"id": 10,
"name": "product 10",
"image": [{
"name": "https://i.imgur.com/eKSk6Fq.jpg",
"width": 900,
"height": 600
}, {
"name": "https://i.imgur.com/np1wmxw.jpg",
"width": 600,
"height": 600
}]
}, {
"id": 11,
"name": "product 11",
"image": [{
"name": "https://i.imgur.com/jlFgGpe.jpg",
"width": 639,
"height": 700
}, {
"name": "https://i.imgur.com/B0D4iRk.jpg",
"width": 1280,
"height": 960
}, {
"name": "https://i.imgur.com/4AiXzf8.jpg",
"width": 540,
"height": 405
}]
}]
我想根据相同的 ID 将 input 分组到一个新的 slice,
所以结果 output 将是具有相同 ID 的分组 image 的新结构的新 slice 。
input 中获取图像大小并想使用 goroutine,我将如何获得结果?自从我上次在这里输入代码playground没有实现正确的输出(总是得到最后的输入)注意:我不知道为什么我在 go playground 中得到 null,但在我的笔记本电脑中结果是:[{"id":11,"name":"product 11","image":[{"名称":"https://i.imgur.com/B0D4iRk.jpg ","宽度":1280,"高度":960}]}]
在 PHP 中,我将执行以下操作以实现预期的输出。
foreach ($input as $key => $value) {
if (!isset($output[$value["id"]])) {
$output[$value["id"]] = [
"id" => $value["id"],
"name" => $value["name"],
"image" => [],
];
}
$get = getimagesize($value["image"]["name"]);
if ($get) {
$width = isset($get[0]) ? $get[0] : 0;
$height = isset($get[1]) ? $get[1] : 0;
}
$output[$value["id"]]["image"][$key] = [
"name" => $value["image"]["name"],
"width" => $width,
"height" => $height,
];
$output[$value["id"]]["image"] = array_values($output[$value["id"]]["image"]);
}
$output = array_values($output);
$json = json_encode($output, true);
echo $json;
谢谢
最佳答案
这里是一个带有示例 json 输入的小示例,使用 map[int] 输出将图像合并到相同的产品 ID 中。
package main
import (
"encoding/json"
"fmt"
"log"
)
type input struct {
ID int `json:"id"`
Name string `json:"name"`
Image img `json:"image"`
}
type output struct {
ID int `json:"id"`
Name string `json:"name"`
Image []img `json:"image"`
}
type img struct {
Name string `json:"name"`
}
func main() {
var jsoninput = []byte(`
[{
"id": 10,
"name": "product 10",
"image": {"name": "image 10a"}
}, {
"id": 10,
"name": "product 10",
"image": {"name": "image 10b"}
}, {
"id": 11,
"name": "product 11",
"image": {"name": "image 11a"}
}, {
"id": 11,
"name": "product 11",
"image": {"name": "image 11b"}
}, {
"id": 11,
"name": "product 11",
"image": {"name": "image 11c"}
}]`)
var inputs []input
err := json.Unmarshal(jsoninput, &inputs)
if err != nil {
log.Fatalln("could not Unmarshal:", err)
}
var outputlist = make(map[int]output)
for _, inp := range inputs {
outputlist[inp.ID] = output{inp.ID, inp.Name, append(outputlist[inp.ID].Image, inp.Image)}
}
var outputs []output
for _, outp := range outputlist{
outputs = append(outputs,outp)
}
jsonoutput, err := json.Marshal(outputs)
fmt.Println(string(jsonoutput))
}
关于Golang 分组并在 goroutine 中按值合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54552516/
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat
我有这样的哈希trial_hash={"key1"=>1000,"key2"=>34,"key3"=>500,"key4"=>500,"key5"=>500,"key6"=>500}我按值降序排列:my_hash=trial_hash.sort_by{|k,v|v}.reverse我现在是这样理解的:[["key1",1000],["key4",500],["key5",500],["key6",500],["key3",500],["key2",34]]但我希望当值相同时按键的升序排序。我该怎么做?例如:上面的散列将以这种方式排序:[["key1",1000],["key3",500
如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只
文章目录git常用命令(简介,详细参数往下看)Git提交代码步骤gitpullgitstatusgitaddgitcommitgitpushgit代码冲突合并问题方法一:放弃本地代码方法二:合并代码常用命令以及详细参数gitadd将文件添加到仓库:gitdiff比较文件异同gitlog查看历史记录gitreset代码回滚版本库相关操作远程仓库相关操作分支相关操作创建分支查看分支:gitbranch合并分支:gitmerge删除分支:gitbranch-ddev查看分支合并图:gitlog–graph–pretty=oneline–abbrev-commit撤消某次提交git用户名密码相关配置g
假设我有一个在Ruby中看起来像这样的哈希:{:ie0=>"Hi",:ex0=>"Hey",:eg0=>"Howdy",:ie1=>"Hello",:ex1=>"Greetings",:eg1=>"Goodday"}有什么好的方法可以将它变成如下内容:{"0"=>{"ie"=>"Hi","ex"=>"Hey","eg"=>"Howdy"},"1"=>{"ie"=>"Hello","ex"=>"Greetings","eg"=>"Goodday"}} 最佳答案 您要求一个好的方法来做到这一点,所以答案是:一种您或同事可以在六个月后理解
有什么区别:@attr[:field]=new_value和@attr.merge(:field=>new_value) 最佳答案 如果您使用的是merge!而不是merge,则没有区别。唯一的区别是您可以在合并参数中使用多个字段(意思是:另一个散列)。例子:h1={"a"=>100,"b"=>200}h2={"b"=>254,"c"=>300}h3=h1.merge(h2)putsh1#=>{"a"=>100,"b"=>200}putsh3#=>{"a"=>100,"b"=>254,"c"=>300}h1.merge!(h2)pu
我正在尝试按Rails相关模型中的字段进行排序。我研究的所有解决方案都没有解决如果相关模型被另一个参数过滤?元素模型classItem相关模型:classPriority我正在使用where子句检索项目:@items=Item.where('company_id=?andapproved=?',@company.id,true).all我需要按相关表格中的“位置”列进行排序。问题在于,在优先级模型中,一个项目可能会被多家公司列出。因此,这些职位取决于他们拥有的company_id。当我显示项目时,它是针对一个公司的,按公司内的职位排序。完成此任务的正确方法是什么?感谢您的帮助。PS-我
我已经有很多两个值数组,例如下面的例子ary=[[1,2],[2,3],[1,3],[4,5],[5,6],[4,7],[7,8],[4,8]]我想把它们分组到[1,2,3],[4,5],[5,6],[4,7,8]因为意思是1和2有关系,2和3有关系,1和3有关系,所以1,2,3都有关系我如何通过ruby库或任何算法来做到这一点? 最佳答案 这是基本Bron–Kerboschalgorithm的Ruby实现:classGraphdefinitialize(edges)@edges=edgesenddeffind_maximum_
如果至少有两个相邻的数字相同,格式为,我需要打包.这是我的输入:[2,2,2,3,4,3,3,2,4,4,5]以及预期的输出:"2:3,3,4,3:2,2,4:2,5"到目前为止我试过:a=[1,1,1,2,2,3,2,3,4,4,5]a.each_cons(2).any?do|s,t|ifs==t如果相等,也许可以尝试计数器,但那是行不通的。 最佳答案 您可以使用Enumerable#chunk_while(如果你使用的是Ruby>=2.3):a.chunk_while{|a,b|a==b}.flat_map{|chunk|chu