根据对象属性将对象数组拆分为PHP中的新数组

时间:2018-10-01 05:12:30

标签: php arrays object split

如何根据对象属性“名称”生成将对象分组的数组?我可以用Javascript做到这一点,但不确定如何用PHP做到这一点。

这是当前json_encoded回显输出的示例片段:

[
    {"id":14970,
    "amount":"70",
    "name":"Food"
    },
    {"id":14970,
    "amount":"100",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"100",
    "name":"Food"
    },
    {"id":14970,
    "amount":"300",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"10",
    "name":"Taxi"
    },
    {"id":14970,
    "amount":"200",
    "name":"Food"
    }
]

这将是所需的输出:

[
    [
        {"id":14970,
        "amount":"70",
        "name":"Food"
        },
        {"id":14970,
        "amount":"100",
        "name":"Food"
        },
        {"id":14970,
        "amount":"200",
        "name":"Food"
        }
    ],
    [
        {"id":14970,
        "amount":"100",
        "name":"Drink"
        },
        {"id":14970,
        "amount":"300",
        "name":"Drink"
        }
    ],
    [
        {"id":14970,
        "amount":"10",
        "name":"Taxi"
        }
    ]
]

如果能解释该解决方案是非常感激的,因为我对PHP的了解有限,并且希望了解它的工作方式,以供将来PHP的参考和使用。

4 个答案:

答案 0 :(得分:1)

<?php
$array = json_decode('[
    {"id":14970,
    "amount":"70",
    "name":"Food"
    },
    {"id":14970,
    "amount":"100",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"100",
    "name":"Food"
    },
    {"id":14970,
    "amount":"300",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"10",
    "name":"Taxi"
    },
    {"id":14970,
    "amount":"200",
    "name":"Food"
    }
]',true);

$types = [];
$splited = [];

foreach($array as $key => $value){
    // searching types for the type
    if(in_array($value['name'],$types)){
        // adding it to splited with the correct key if type exists
        $splited[array_search($value['name'],$types)][] = $value;
    } else {
        // creating a new type if not exists
        $types[] = $value['name'];
        $splited[] = [$value];
    }
}

echo '<pre>';
var_dump($splited);
echo '</pre>';
?>

答案 1 :(得分:1)

使用数组中的名称作为多维数组的组(键)。

$array = json_decode('[
{"id":14970,
"amount":"70",
"name":"Food"
},
{"id":14970,
"amount":"100",
"name":"Drink"
},
{"id":14970,
"amount":"100",
"name":"Food"
},
{"id":14970,
"amount":"300",
"name":"Drink"
},
{"id":14970,
"amount":"10",
"name":"Taxi"
},
{"id":14970,
"amount":"200",
"name":"Food"
}
]',true);

$result = [];
foreach($array as $key=>$value){
    $group = $value['name'];
    if(!isset($result[$group])) $result[$group ] = [];

    $result[$group][] = $value;
}

//remove the top level keys, it's easier to build it with them
$result = array_values($result); 

输出

 array (
  0 => 
  array (
    0 => 
    array (
      'id' => 14970,
      'amount' => '70',
      'name' => 'Food',
    ),
    1 => 
    array (
      'id' => 14970,
      'amount' => '100',
      'name' => 'Food',
    ),
    2 => 
    array (
      'id' => 14970,
      'amount' => '200',
      'name' => 'Food',
    ),
  ),
  1 => 
  array (
    0 => 
    array (
      'id' => 14970,
      'amount' => '100',
      'name' => 'Drink',
    ),
    1 => 
    array (
      'id' => 14970,
      'amount' => '300',
      'name' => 'Drink',
    ),
  ),
  2 => 
  array (
    0 => 
    array (
      'id' => 14970,
      'amount' => '10',
      'name' => 'Taxi',
    ),
  ),
)

Sandbox

然后,您只需要对其进行json_encode。

 $result = [];
 foreach($array as $key=>$value){
     $group = $value['name'];
     if(!isset($result[$group])) $result[$group ] = [];

     $result[$group][] = $value;
 }

 echo json_encode(array_keys($result), JSON_PRETTY_PRINT);

哪个给:

[
    [
        {
            "id": 14970,
            "amount": "70",
            "name": "Food"
        },
        {
            "id": 14970,
            "amount": "100",
            "name": "Food"
        },
        {
            "id": 14970,
            "amount": "200",
            "name": "Food"
        }
    ],
    [
        {
            "id": 14970,
            "amount": "100",
            "name": "Drink"
        },
        {
            "id": 14970,
            "amount": "300",
            "name": "Drink"
        }
    ],
    [
        {
            "id": 14970,
            "amount": "10",
            "name": "Taxi"
        }
    ]
]

Sandbox

答案 2 :(得分:1)

上面提到的对象数组看起来像JSON格式。我已经转换成数组并将其分组。请尝试此操作可能对您有帮助:)

$objStr = '[
    {"id":14970,
    "amount":"70",
    "name":"Food"
    },
    {"id":14970,
    "amount":"100",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"100",
    "name":"Food"
    },
    {"id":14970,
    "amount":"300",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"10",
    "name":"Taxi"
    },
    {"id":14970,
    "amount":"200",
    "name":"Food"
    }
]';
$arr = json_decode($objStr,true);
$arrArr = array();
foreach($arr as $k => $arrOfArr) {
    $arrArr[$arrOfArr['name']][] = $arrOfArr;
}
echo "<pre>"; print_r($arrArr); echo "</pre>";

答案 3 :(得分:1)

<ion-navbar *navbar>
 <button menuToggle>
  <ion-icon name="menu"></ion-icon>
 </button>
 <ion-title>Ionic2 + Google Calendar</ion-title>
</ion-navbar>

<ion-content padding class="getting-started">
 <ion-list> 
 <ion-item-group>
   <ion-item-divider light>Event Details</ion-item-divider>
     <ion-item>
       <ion-label>Name</ion-label>
       <ion-input type="text" [(ngModel)]="calendarEvent.name"></ion-input>
     </ion-item>
     <ion-item>
       <ion-label>Location</ion-label>
       <ion-input type="text" [(ngModel)]="calendarEvent.location"></ion-input>
     </ion-item>
     <ion-item>
       <ion-label>Description</ion-label>
       <ion-input type="text" [(ngModel)]="calendarEvent.description"></ion-input>
     </ion-item>
     <ion-item>
       <ion-label>Start Date</ion-label>
        <ion-datetime displayFormat="DD MMM YYYY" pickerFormat="DD MMM YYYY" [(ngModel)]="calendarEvent.startDate"></ion-datetime>
     </ion-item>
     <ion-item>
       <ion-label>Start Time</ion-label>
       <ion-datetime displayFormat="hh:mm:a" pickerFormat="hh:mm:a" [(ngModel)]="calendarEvent.startTime"></ion-datetime>
     </ion-item>
     <ion-item>
       <ion-label>End Date</ion-label>
       <ion-datetime displayFormat="DD MMM YYYY" pickerFormat="DD MMM YYYY" [(ngModel)]="calendarEvent.endDate"></ion-datetime>
     </ion-item>
     <ion-item>
       <ion-label>End Time</ion-label>
        <ion-datetime displayFormat="hh:mm:a" pickerFormat="hh:mm:a" [(ngModel)]="calendarEvent.endTime"></ion-datetime>
     </ion-item>
    <ion-item-group>
    <ion-item-divider light>Attendees</ion-item-divider>
     <ion-list>
        <ion-item *ngFor="let attendee of attendees;let i = index" inset>
            <ion-label>Attendee {{attendees.length - i}}</ion-label>
            <ion-input [(ngModel)]="attendee.email"></ion-input>
            <ion-icon name="md-remove-circle" item-right class="addRemoveBtn" (click)="removeAttendees(i)" *ngIf="attendees.length - i < attendees.length"></ion-icon>
            <ion-icon name="md-add-circle" item-right class="addRemoveBtn" (click)="addAttendees()" *ngIf="attendees.length - i  == attendees.length"></ion-icon>
         </ion-item>
     </ion-list>
   </ion-item-group>

  </ion-item-group>
 </ion-list>
<button primary (click)="sendInvite()">Send Google Calendar Invite</button>

</ion-content>