我怎么可以将这个数组分为
[Product_1] => Array
(
[0] Silver
[1] Black
[2] Red
)
[Product_2] => Array
(
[0] Silver
[1] Gold
[2] Black
)
有人可以帮忙吗?
或您可以简单地使用
array_walk
$result = [];
array_walk($array,function($v,$k)use(&$result){$result[$v[0]][] = $v[1];});
print_r($result);
输出:
Array
(
[Product_1] => Array
(
[0] => Gold
[1] => Silver
[2] => Black
[3] => Red
)
[Product_2] => Array
(
[0] => Silver
[1] => Gold
[2] => Black
)
)
循环通过您的
$array
,然后将每个颜色值推到具有产品名称为键的数组。
输出:
$array = [
['Product_1', 'Gold'],
['Product_1', 'Silver'],
['Product_1', 'Black'],
['Product_1', 'Red'],
['Product_2', 'Silver'],
['Product_2', 'Gold'],
['Product_2', 'Black'],
];
$result = [];
foreach ($array as $values) {
list ($product, $color) = $values;
$result[$product][] = $color;
}
print_r($result);