嗨我正在尝试显示具有相同类型但值不同的数组。
如何根据值“CAT”以分组方式显示此数组?
我的阵列:
$options = array(
array("cat" => "Impresoras","nameProd" => "Impresora 4"),
array("cat" => "Destructoras","nameProd" => "Destructora 3"),
array("cat" => "Impresoras","nameProd" => "Impresora 8"),
array("cat" => "Destructoras","nameProd" => "Destructora 5")
);
我需要打印:
Impresoras:Impresora 4,Impresora 8
Destructoras:Destructora 3,Destructora 5
答案 0 :(得分:1)
创建一个以cat
为关键字的新数组。喜欢这样;
$grouped_categories = array();
foreach ( $options as $option ) {
$grouped_categories[$option['cat']][] = $option['nameProd'];
}
这将输出类似的内容
[
'Impresoras' => ['Impresora 4', 'Impresora 8']
'Destructoras' => [...]
]
您希望如何输出该数组取决于您。
答案 1 :(得分:1)
试试这个
$options = array(
array("cat" => "Impresoras","nameProd" => "Impresora 4"),
array("cat" => "Destructoras","nameProd" => "Destructora 3"),
array("cat" => "Impresoras","nameProd" => "Impresora 8"),
array("cat" => "Destructoras","nameProd" => "Destructora 5")
);
foreach ($options as $key => $value) {
$nArray[$value['cat']][] = $value['nameProd'];
}
foreach ($nArray as $key => $value) {
echo $key.":".implode(",", $value)."<br>";
}
<强>输出强>
Impresoras:Impresora 4,Impresora 8
Destructoras:Destructora 3,Destructora 5
答案 2 :(得分:0)
$data = [];
$options = array(
array("cat" => "Impresoras", "nameProd" => "Impresora 4"),
array("cat" => "Destructoras", "nameProd" => "Destructora 3"),
array("cat" => "Impresoras", "nameProd" => "Impresora 8"),
array("cat" => "Destructoras", "nameProd" => "Destructora 5")
);
foreach ($options as $key => $value) {
$data[$value['cat']][] = $value['nameProd'];
};