我有這個原始數組在我的代碼php:如何合併和求和相同鍵值的數組的值?
[
{
"source": {
"id": 2,
"name": "Cairo"
},
"destination": [
{
"count": 3,
"name": "Alex",
"price": 2000,
"discount": null,
"distance": 12,
"new": false
},
{
"count": 4,
"name": "Alex",
"price": 2000,
"discount": null,
"distance": 12,
"new": false
}
]
},
{
"source": {
"id": 1,
"name": "Zagazig"
},
"destination": [
{
"count": 1,
"name": "Alex",
"price": 200,
"discount": null,
"distance": 100,
"new": false
},
{
"count": 1,
"name": "Cairo",
"price": 1000,
"discount": null,
"distance": 100,
"new": false
},
{
"count": 1,
"name": "Cairo",
"price": 1000,
"discount": null,
"distance": 100,
"new": false
}
]
}
]
在目標數組
,如果像亞歷克斯或開羅每個對象被重複的名字,我想給它一個對象合併,只有一個對象與開羅的名字,以及名稱alex和計算或sume計數鍵的一個對象
我想要這個結果................ ............ ...
[
{
"source": {
"id": 2,
"name": "Cairo"
},
"destination": [
{
"count": 7,
"name": "Alex",
"price": 2000,
"discount": null,
"distance": 12,
"new": false
}
]
},
{
"source": {
"id": 1,
"name": "Zagazig"
},
"destination": [
{
"count": 1,
"name": "Alex",
"price": 200,
"discount": null,
"distance": 100,
"new": false
},
{
"count": 2,
"name": "Cairo",
"price": 1000,
"discount": null,
"distance": 100,
"new": false
},
]
}
]
如果您不努力解決您的問題,爲什麼我/我們?爲了讓你開始使用'json_deocde(...,true)',你可以擺脫這些對象,並且可以在整個過程中使用數組語法。之後,你可能需要'foreach'和'if'。 – jh1711