gpt4 book ai didi

arrays - 在 PHP 中合并和添加 2 个 JSON 提要的值

转载 作者:行者123 更新时间:2023-12-01 14:35:22 26 4
gpt4 key购买 nike

我正在尝试为一个已经在 J​​SON 中列出成分的网站编写一个购物 list 应用。

完整代码在底部,只是为了解释;我的目标是能够合并 2 个数组,在“名称”(最好还有“度量”)匹配时添加“数量”中的值。

例如“向日葵油”列在两个 JSON 提要中。我希望它输出为:

{"name":"Sunflower oil","quantity":110,"measure":"ml"}

但它目前覆盖了 JSON,输出是:

{"name":"Sunflower oil","quantity":10,"measure":"ml"},

对于我做错的任何帮助将不胜感激,因为 JSON 和对象/数组不是我的强项!

提前致谢 - 这是我的代码:

<?php
$a = '{"ingredients":[{"name": "Sunflower oil","quantity": 100,"measure": "ml"}]}';
$b = '{"ingredients":[{"name": "Sunflower oil","quantity": 10,"measure": "ml"},{"name": "Fennel seeds","quantity": 1,"measure": "teaspoon"},{"name": "Garlic","quantity": 1,"measure": "clove"}]}';
print_r( json_encode(array_merge(json_decode($a, true),json_decode($b, true))) );
?>

最佳答案

您可以使用以下代码来获得预期的结果:

<?php
$a = '{"ingredients":[{"name": "Sunflower oil","quantity": 100,"measure": "ml"},{"name": "Olive oil","quantity": 50,"measure": "ml"}]}';
$b = '{"ingredients":[{"name": "Sunflower oil","quantity": 10,"measure": "ml"},{"name": "Fennel seeds","quantity": 1,"measure": "teaspoon"},{"name": "Garlic","quantity": 1,"measure": "clove"}]}';

$aArr = json_decode($a, true);
$bArr = json_decode($b, true);
$sumArr = array("ingredients" => array());

foreach ($aArr['ingredients'] as $valA) {
foreach ($bArr['ingredients'] as $keyB => $valB) {
if ($valA['name'] == $valB['name'] &&
$valA['measure'] == $valB['measure']) {

$valA['quantity'] += $valB['quantity'];
$sumArr['ingredients'][] = $valA;

unset($bArr['ingredients'][$keyB]);
continue 2;
}
}
$sumArr['ingredients'][] = $valA;
}
$sumArr['ingredients'] = array_merge($sumArr['ingredients'], $bArr['ingredients']);
print_r( json_encode( $sumArr ));
?>

关于arrays - 在 PHP 中合并和添加 2 个 JSON 提要的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27407423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com