Php 如何在一定条件下将给定数组转换为新数组?
我有这个数组,我想从中创建一个新数组Php 如何在一定条件下将给定数组转换为新数组?,php,arrays,Php,Arrays,我有这个数组,我想从中创建一个新数组 Array( [0] => stdClass Object( [name] => Sam [product] => Candy [group] => 1 ) [1] => stdClass Object ( [name] => Sam [product] => Chocolate [group
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,我不知道怎么做。请帮忙!
谢谢
如果
$result
中的键对您很重要,请在之后使用重置它们。您是否愿意与我们分享这些“条件”,或者我们是否可以推断?您想将stdClass转换为array?实际上,我想将产品与相同的groupuse foreach循环组合,并使用key作为条件,对于该条件,第一个数组的所有元素都将添加到第二个数组中。
$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;
}
}