如何将给定数组转换为具有某些条件的新数组?

时间:2015-10-14 10:02:51

标签: php arrays

我有这个数组,我想从中创建一个新的数组

Array(
[0] => stdClass Object(
        [name] => Sam      
        [product] => Candy
        [group] => 1
    )

[1] => stdClass Object
    (
        [name] => Sam
        [product] => Chocolate
        [group] => 1
    )

[2] => stdClass Object(
        [name] => Dany
        [product] => Mobile
        [group] => 3
    )

[3] => stdClass Object(
        [name] => Dany
        [product] => Laptop
        [group] => 3
    )

[4] => stdClass Object
    (
        [name] => Dany
        [product] => Computer
        [group] => 3
    ) )

从这个数组中,我想创建一个新数组,其中包含具有相同组的产品:

Array(
[0] => array(
        [name] => Sam      
        [product] =>array( Candy, Chocolate)
        [group] => 1
    )

[1] => array(
        [name] => Dany
        [product] =>array( Mobile, Laptop, Computer)
        [group] => 3
    ) )

我在php工作,我不知道该怎么做。请帮忙! 感谢

1 个答案:

答案 0 :(得分:1)

$result = [];
foreach ($array as $value) {
    if (isset($result[$value->group])) {
        $result[$value->group]['product'][] = $value->product;
    } else {
        $value->product = (array)$value->product;
        $result[$value->group] = (array)$value;
    }
}

如果$result中的密钥对您很重要,请稍后再使用array_values重置密码。