我有一个包含3个属性的php对象(书):name, category, description
然后,我在数组中列出了这些book
个对象。
我想为按category
分组的这些对象创建一个新的关联数组。
假设我在名为$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
如何创建名为$categories
$categories['cat1'] = array(book1, book2)
$categories['cat2'] = array(book2)
$categories['cat3'] = array(book3)
哪本书?是书对象,而不是单词
答案 0 :(得分:41)
像这样:
foreach($books as $book)
{
$categories[$book->category][] = $book;
}
答案 1 :(得分:4)
只需将对象数组循环到一个新数组中,其中键为类别:
$newArray = array();
foreach($array as $entity)
{
if(!isset($newArray[$entity->category]))
{
$newArray[$entity->category] = array();
}
$newArray[$entity->category][] = $entity;
}
这是你在找什么?
代码说明:
/*
* 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;
}
答案 2 :(得分:4)
您可以使用ouzo goodies:
执行此操作 $categories = Arrays::groupBy($books, Functions::extractField('category'));
请参阅:http://ouzo.readthedocs.org/en/latest/utils/arrays.html#groupby
答案 3 :(得分:0)
$categories = array();
for ($i = 0; $i < count($books); $i++){
if (isset($categories[$books[$i]->category]) == false)
$categories[$books[$i]->category] = array();
$categories[$books[$i]->category][] = $books[$i]
}
欢呼声
答案 4 :(得分:0)
试试这个:
$categories = array();
foreach ($books as $book){
if (!array_key_exists($book->category , $categories))
$categories[$book->category] = array();
$categories[$book->category][] = $book;
}
答案 5 :(得分:0)
这应该有效:
$categories = array();
foreach ($books as $book) {
$categories[$book['category']][] = $book;
}
答案 6 :(得分:0)
我遇到了类似的问题,但是使用wordpress和metavalues / metakeys有点复杂(其中$ results是从$ wpdb-&gt; get_results()查询中获取的关联数组数组。
这是我的解决方案适应您的问题:
$categories = array();
foreach ($results as $row) {
$id = $row['category'];
$description = $row['category'];
$name = $row['name']
if (!isset($categories[$id])) {
$categories[$id] = array();
}
$categories[$id] = array_merge($categories[$id], 'description'=>$description , 'name'=>$name);
}
然后你可以运行另一个for循环来从categories数组中获取每个数组:
foreach ($categories as $category) {
var_dump($category);
}
答案 7 :(得分:0)
如果要通过从带有或不带有附加参数的特定方法获取密钥来对对象进行分组,则可以使用this library方法:
Arr::groupObjects(array $objects, string $method, ...$args): array