Laravel中的JSON元素的人工操作
我尝试使用JSON文件进行一些操作。
例如,我打算减去它们。但是问题在于可能有不同的关键要素。
$a1=[
{"cat":2,"total":1},
{"cat":11,"total":23},
{"cat":13,"total":30}
];
$a2=[
{"cat":2,"total":15},
{"cat":11,"total":13},
{"cat":15,"total":70},
{"cat":16,"total":40}
];
结果一定是
$result=[
{"cat":2,"total":14},
{"cat":11,"total":-10},
{"cat":13,"total":-30},
{"cat":15,"total":70},
{"cat":16,"total":40}
]
我试图在循环中采用元素,但我不能。
您能告诉我做这项工作的方式吗?
I try to make some operations with JSON files.
For example I intend to subtract them. But the problem is there can be different key elements.
$a1=[
{"cat":2,"total":1},
{"cat":11,"total":23},
{"cat":13,"total":30}
];
$a2=[
{"cat":2,"total":15},
{"cat":11,"total":13},
{"cat":15,"total":70},
{"cat":16,"total":40}
];
and result must be
$result=[
{"cat":2,"total":14},
{"cat":11,"total":-10},
{"cat":13,"total":-30},
{"cat":15,"total":70},
{"cat":16,"total":40}
]
I have tried to take elements in a loop but I could not.
would you please show me the way to make this work ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,代码:
说明:
$ s
和$ key
中搜索匹配$ key
$ f
在第二次搜索比赛
简而默认为0,然后我第一个循环添加第二个没有匹配的元素。
First, the code:
Explanation:
json_decode
and I set the second parameter totrue
to make sure they will be associative arrays$s
and$key
so I will see these variables in the closure of the function$key
with it$f
In short, I loop the second and subtract the matching first if they exist, defaulting to 0 and then I loop the first to add the elements that do not have a match in the second.