按对象属性分组php对象数组

Joh*_*ohn 14 php

我有一个带有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)

  • 如果您找到了这个答案并且没有立即意识到它在做什么——它正在创建一个新数组(名为“$categories”),其中每个值的键都为“$book->category”。每个键的值是一个与该 `$book->category` 对应的 `$book` 对象数组。如果它在此评论中看起来不像泥土,我会制作一张 ASCII 图片。 (2认同)

Rob*_*itt 5

只需将对象数组循环到一个新数组中,键为类别:

$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)