我有以下数组
这是由$ product_attribute数组
生成的Array
(
[Color] => Array
(
[950981-YB051314-01] => Green
[950981-YB051314-02] => Green
[950981-YB051314-03] => Green
)
[Size] => Array
(
[950981-YB051314-01] => M
[950981-YB051314-02] => L
[950981-YB051314-03] => XL
)
)
我试过这个
<?php foreach($product_attribute as $keys=>$value) { ?>
<ul class="selections">
<?php $skus = array(); ?>
<?php foreach(array_unique($value) as $key => $vals) { ?>
<?php foreach($value as $key => $val) { ?>
<?php array_push($skus, $key); ?>
<?php } ?>
<?php $sku = implode(';', array_unique($skus)); ?>
<li data-sku="<?php echo $keys; ?>"><?php echo rtrim($vals, ','); ?></li>
<?php } ?>
</ul>
<?php } ?>
但上面的代码就像
一样<li data-sku="950981-01;950981-02;950981-03">Green</li>
<li data-sku="950981-01;950981-02;950981-03">M</li>
<li data-sku="950981-01;950981-02;950981-03">L</li>
<li data-sku="950981-01;950981-02;950981-03">XL</li>
将以下内容视为预期输出
<li data-sku="950981-01;950981-02;950981-03">Green</li>
<li data-sku="950981-01">M</li>
<li data-sku="950981-02">L</li>
<li data-sku="950981-03">XL</li>
任何人都可以解释如何处理这种情况。
答案 0 :(得分:1)
问题似乎是“按值组密钥”。这样做:
$product_attribute = array(
'color' => array(
'1' => 'green',
'2' => 'green',
'3' => 'green'
),
'size' => array(
'4' => 'M',
'5' => 'L',
'6' => 'XL'
),
);
foreach($product_attribute as $param){
$values = array_unique($param); // fetch unique values - green,M,L,XL
foreach($values as $value){
$keys = array_keys($param,$value); // keys by unique value
print '<li data-sku="'.implode(';',$keys).'">'.$value.'</li>';
}
}
//OUTPUT
<li data-sku="1;2;3">green</li>
<li data-sku="4">M</li>
<li data-sku="5">L</li>
<li data-sku="6">XL</li>