我有这样的数组:
$array[] = "BRAND A|PERIOD 1|RANGE 1";
$array[] = "BRAND A|PERIOD 1|RANGE 2";
$array[] = "BRAND A|PERIOD 1|RANGE 3";
$array[] = "BRAND A|PERIOD 2|RANGE 1";
$array[] = "BRAND A|PERIOD 2|RANGE 2";
$array[] = "BRAND A|PERIOD 2|RANGE 3";
$array[] = "BRAND A|PERIOD 3|RANGE 1";
$array[] = "BRAND A|PERIOD 3|RANGE 2";
$array[] = "BRAND A|PERIOD 3|RANGE 3";
$array[] = "BRAND B|PERIOD 1|RANGE 1";
$array[] = "BRAND B|PERIOD 1|RANGE 2";
$array[] = "BRAND B|PERIOD 1|RANGE 3";
我想得到以下结果:
BRAND A: [PERIOD 1] [PERIOD 2] [PERIOD 3]
BRAND B: [PERIOD 1]
我尝试使用 for 循环,使用它列出并分解所有值,然后array_unique删除 $brand 中的重复项并$period数组值,最后是两个 foreach 嵌套循环......但我没有得到比这更好的结果:
BRAND A: [PERIOD 1] [PERIOD 2] [PERIOD 3]
BRAND B: [PERIOD 1] [PERIOD 2] [PERIOD 3]
"品牌 B"数组仅包含一个唯一值:周期 1,但脚本会打印"品牌 A"数组中的所有唯一值。
这是我的代码:
for($i = 0; $array[$i]; $i++):
list($brand, $period, $range) = explode("|", $array[$i]);
$array_brand[] = $brand;
$unique_brand = array_unique($array_brand);
$array_period[] = $period;
$unique_period = array_unique($array_period);
endfor;
foreach($unique_brand as $value_brand):
echo $value_brand . ": ";
foreach($unique_period as $value_period):
echo "[" . $value_period . "] ";
endforeach;
echo "<br />";
endforeach;
非常欢迎任何获得所需结果的建议。 提前谢谢。
我还没有测试过这段代码,但我认为它给了你想要的。
$array[] = "BRAND A|PERIOD 1|RANGE 1";
$array[] = "BRAND A|PERIOD 1|RANGE 2";
$array[] = "BRAND A|PERIOD 1|RANGE 3";
$array[] = "BRAND A|PERIOD 2|RANGE 1";
$array[] = "BRAND A|PERIOD 2|RANGE 2";
$array[] = "BRAND A|PERIOD 2|RANGE 3";
$array[] = "BRAND A|PERIOD 3|RANGE 1";
$array[] = "BRAND A|PERIOD 3|RANGE 2";
$array[] = "BRAND A|PERIOD 3|RANGE 3";
$array[] = "BRAND B|PERIOD 1|RANGE 1";
$array[] = "BRAND B|PERIOD 1|RANGE 2";
$array[] = "BRAND B|PERIOD 1|RANGE 3";
$res = [];
foreach ($array as $str) {
$items = explode('|', $str);
if (! array_key_exists($items[0], $res)) {
$res[$items[0]] = [];
}
if (! in_array($items[1], $res[$items[0]])) {
$res[$items[0]][] = $items[1];
}
}
foreach ($res as $k => $v) {
sort($res[$k]);
echo $k . ": ";
foreach ($v as $y){
echo "[" . $y . "] ";
}
echo "<br />";
}
您可以使用一个循环来执行此操作。
$brands = [
'a' => [],
'b' => []
];
foreach($array as $arr) {
$rowData = explode('|', $arr);
if($rowData[0] == 'BRAND A' && !in_array($rowData[1], $brands['a'])) {
array_push($brands['a'], $rowData[1]);
}
if($rowData[0] == 'BRAND B' && !in_array($rowData[1], $brands['b'])) {
array_push($brands['b'], $rowData[1]);
}
}
这将为您提供结果:
$brands = [
'a' => [
'PERIOD 1',
'PERIOD 2',
'PERIOD 3'
],
'b' => [
'PERIOD 1'
]
];