我有一个带有3个属性的php对象(书):name, category, description
然后我book在数组中有这些对象的列表.我想为这些按对象分组的对象创建一个新的关联数组category.
假设我在一个名为的数组中有4个书对象 $books
name category description
==================================
book1 cat1 this is book 1
book2 cat1 this is book 2
book3 cat2 this is book 3
book4 cat3 this is book 4
Run Code Online (Sandbox Code Playgroud)
如何创建一个名为的关联数组 $categories
$categories['cat1'] = array(book1, book2)
$categories['cat2'] = array(book2)
$categories['cat3'] = array(book3)
Run Code Online (Sandbox Code Playgroud)
哪本书?是书的对象,而不是单词
Aka*_*run 45
像这样:
foreach($books as $book)
{
$categories[$book->category][] = $book;
}
Run Code Online (Sandbox Code Playgroud)
只需将对象数组循环到一个新数组中,键为类别:
$newArray = array();
foreach($array as $entity)
{
if(!isset($newArray[$entity->category]))
{
$newArray[$entity->category] = array();
}
$newArray[$entity->category][] = $entity;
}
Run Code Online (Sandbox Code Playgroud)
这是您要找的吗?
代码解释:
/*
* Create a new blank array, to store the organized data in.
*/
$newArray = array();
/*
* Start looping your original dataset
*/
foreach($array as $entity)
{
/*
* If the key in the new array does not exists, set it to a blank array.
*/
if(!isset($newArray[$entity->category]))
{
$newArray[$entity->category] = array();
}
/*
* Add a new item to the array, making shore it falls into the correct category / key
*/
$newArray[$entity->category][] = $entity;
}
Run Code Online (Sandbox Code Playgroud)