开发者

How to split an array via value change on one of the keys?

开发者 https://www.devze.com 2023-04-12 14:17 出处:网络
I have a returned the rows from a database and joined from another table to get a brand for each product, I want to be able to split

I have a returned the rows from a database and joined from another table to get a brand for each product, I want to be able to split

Array(
    [0] => stdClass Object
        (
            [pid] => 1
            [prodref] => F50
            [brand] => 1
            [name] => Adidas
        )

    [1] => stdClass Object
        (
开发者_StackOverflow中文版            [pid] => 3
            [prodref] => Mercurial
            [brand] => 2
            [name] => Nike
        )
)

This is a simplified version but I have four brands and on the database query I have ordered by brand then by prodref, so I want to be able to split the array by the brand key - so I can show all the Adidas products in different areas of the page with only one database query.


foreach ($rows as $row) {
    $result[$row->name][] = $row;
}


If you only have very specific cases, like a property inside has a value like the brand being 2, you can overload the array and then just use as you see fit:

# $rows is your resultset
$rows = function($filter = NULL, $prop = 'brand') use ($rows)
{
    if(!$filter) return $rows;
    $subset = array();
    foreach($rows as $row)
        if ($row->$prop == $filter) $subset[] = $row;
    return $subset;
};

If you later on want to output all $rows:

foreach($rows() as $row) ...

Or if you want to get all rows with brand 2:

foreach($rows(2) as $row) ...

or 1:

foreach($rows(1) as $row) ...

And finally if you want to get the subset by some other property:

foreach($rows('Adidas', 'name') as $row) ...

If your application grows, you should take a look into the SPL and the Iterators it offers.

0

精彩评论

暂无评论...
验证码 换一张
取 消