我正在尝试为一个网站编写一个购物清单应用程序,该网站已经以 JSON 列出了成分。
完整代码在底部,但只是为了解释;我的目标是能够合并两个数组,当“名称”(最好还有“度量”)匹配时添加“数量”中的值。
例如两个 JSON feed 中均列出了“葵花籽油”。 我希望它输出为:
{"name":"Sunflower oil","quantity":110,"measure":"ml"}
但它当前覆盖了 JSON 并且输出是:
{"name":"Sunflower oil","quantity":10,"measure":"ml"},
这是我的代码:
<?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))) );
?>
所需输出:
{
"ingredients": [
{
"name": "Sunflower oil",
"quantity": 110,
"measure": "ml"
},
{
"name": "Olive oil",
"quantity": 50,
"measure": "ml"
},
{
"name": "Fennel seeds",
"quantity": 1,
"measure": "teaspoon"
},
{
"name": "Garlic",
"quantity": 1,
"measure": "clove"
}
]
}
您可以使用以下代码来获得预期的结果:
<?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 ));
?>
ingredients
。代码:(演示)
$ingred1 = json_decode($a, true)['ingredients'];
$ingred2 = json_decode($b, true)['ingredients'];
$result = [];
foreach (array_merge($ingred1, $ingred2) as $item) {
$groupBy = $item['name'] . '_' . $item['measure'];
if (!isset($ref[$groupBy])) {
$ref[$groupBy] = $item;
$result[] =& $ref[$groupBy];
continue;
}
$ref[$groupBy]['quantity'] += $item['quantity'];
};
echo json_encode(['ingredients' => $result], JSON_PRETTY_PRINT);