将PHP对象数组按对象属性分组

20

我有一个PHP对象(book),包含3个属性: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

我该如何创建一个名为$categories的关联数组?

$categories['cat1'] = array(book1, book2)
$categories['cat2'] = array(book2)
$categories['cat3'] = array(book3)

book? 是指书本对象而非单词

8个回答

61
就像这样:
foreach($books as $book)
{ 
    $categories[$book->category][] = $book;
}

2
如果你找到了这个答案,但还不清楚它在做什么——它正在创建一个名为$categories的新数组,并为每个$book->category的值创建一个键。每个键的值是对应于该$book->category$book对象数组。如果不是在该评论中看起来像泥巴,我会画一个ASCII图片的。 - Travis Hohl
1
如果您想对类别进行排序,可以使用ksort($categories);。请参见http://php.net/manual/en/function.ksort.php。 - Travis Hohl

5

只需将对象数组循环到带有类别键的新数组中:

$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;
}

4

1
$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]
}

干杯


0

试试这个:

$categories = array();
foreach ($books as $book){

  if (!array_key_exists($book->category , $categories))
     $categories[$book->category] = array();

  $categories[$book->category][] = $book;

}

0

这应该可以工作:

$categories = array();
foreach ($books as $book) {

    $categories[$book['category']][] = $book;

}

与JavaScript不同,您不能使用数组[propertyName]语法访问对象属性。 - rink.attendant.6

0

我曾经遇到过类似的问题,但是在 WordPress 和 metavalues/metakeys 中更加复杂(其中 $results 是从 $wpdb->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循环来从类别数组中获取每个数组:
foreach ($categories as $category) {
    var_dump($category);
}

0
如果你想通过从特定方法获取键来对对象进行分组,无论是否有额外参数,你可以使用这个库的方法:this library
Arr::groupObjects(array $objects, string $method, ...$args): array

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接