php

时间:2019-03-28 12:57:37

标签: php

我遇到了问题: 我试图在JSON中总计所有值相同的“ id” 示例:

[{id: "100002475575341", name: "N1", point: "2"},
 {id: "100002993363229", name: "N2", point: "2"},
 {id: "100002993363229", name: "N2", point: "2"},
 {id: "100002475575341", name: "N1", point: "2"}]

和预期结果:

[{id: "100002475575341", name: "N1", point: "4"},
 {id: "100002993363229", name: "N2", point: "4"}]

2 个答案:

答案 0 :(得分:1)

注意:我通过在索引名称周围添加引号来将您的JSON字符串更改为有效

将JSON解码为数组,然后循环。将其添加到$results索引的name数组中。如果元素存在,则将这些点加在一起。如果不存在,请创建它。

$json = '[{"id": "100002475575341", "name": "N1", "point": "2"},
          {"id": "100002993363229", "name": "N2", "point": "2"},
          {"id": "100002993363229", "name": "N2", "point": "2"},
          {"id": "100002475575341", "name": "N1", "point": "2"}]';

$array = json_decode($json);
$result = [];

foreach ($array as $a) {
    if (isset($result[$a->name])) {
        $result[$a->name]->point += $a->point;
    } else {
        $result[$a->name] = $a;
    }
}

$output = json_encode(array_values($result));

答案 1 :(得分:0)

我以您的代码为例,您可以尝试

注意:我更改了您的JSON,因为它是无效的JSON格式。

<div (ionChange)="Trigger()">
    <ion-select [(ngModel)]="ListRooms" (ionChange)="GetRoomId($event)">
      <ion-option *ngFor="let room of rooms" value="{{room.ID}}">{{room.DESCRIPTION}}</ion-option>
    </ion-select>
    <ion-item>
      <ion-label>DATE</ion-label>
      <ion-datetime [(ngModel)]="room_date" displayFormat="DD/MM/YYYY"></ion-datetime>
    </ion-item>
  </div>