make array_unique用于停止每个重复

时间:2017-01-19 04:47:53

标签: php

我对每个循环都有三个是不必要的

<?php foreach($Categories as $Category){ ?>

<div id="accordion" data-accordion="" class="left_sub_menu">
        <h3 class="accordion"><?=$Category['category_name']?></h3>              
            <div class="panel">
                <ul>
                <?php foreach($Category['Product_name'] as $product){ ?>
                <?php foreach($Category['Product_slug'] as $slug){ ?>
                <?php // $product = array_unique($product['name']); ?> 

                <li><a href="<?=Base_url()?>products/<?=$slug?>" ><?=$product;?></a></li>
                <?php } ?>
                <?php  } ?>
                </ul>
            </div>      
<?php } ?>

但$ products会重复如何阻止它重复请帮助

输入数组是:

[0] => Array (
    [category_name] =>Starting System
    [category_id] => 5
    [ Product_slug] => Array (
        [0] => starting_system
        [1] => pow-r-quik_air
        [2] => gali_air
        [3] => hydraulic_starter
        ....
        [8] => spring_starter
    )
    [Product_name] => Array (
        [0] => Starting System
        [1] => Pow-R-Quik Air
        [2] => Gali Air
        ...
        [8] => Spring Starter
    )
  )
) 

1 个答案:

答案 0 :(得分:0)

由于“slugs”=产品的数量,你可以绕它们做一个for循环。

(注意 - 有更好的答案和代码可以改进很多,但这是最简单的让你去。)

<?php foreach($Categories as $Category){ ?>

<div id="accordion" data-accordion="" class="left_sub_menu">
        <h3 class="accordion"><?=$Category['category_name']?></h3>              
            <div class="panel">
                <ul>
                <?php for ($i=0; $i < count($Category['Product_name']); ++$i)){ ?>
                <?php $product = $Category['Product_name'][$i]; ?> 
                <?php $slug = $Category['Product_slug'][$i]; ?> 

                <li><a href="<?=Base_url()?>products/<?=$slug?>" ><?=$product;?></a></li>
                <?php  } ?>
                </ul>
            </div>      
<?php } ?>

编辑:快速重写代码。更清楚地发生了什么,这将有助于调试你所拥有的</div>

<?php
$output = '';

foreach($Categories as $Category) {
    $numItems = count($Category['Product_name']);

    $output .= '

    <div id="accordion" data-accordion="" class="left_sub_menu">
        <h3 class="accordion">' . htmlspecialchars($Category['category_name']) . '</h3>              
        <div class="panel">
            <ul>';

    for ($i=0; $i < $numItems; ++$i) {
        if (isset($Category['Product_slug'][$i])) {
            $output .= '<li><a href="' . Base_url() . 'products/' . htmlspecialchars(urlencode($Category['Product_slug'][$i])) . '">' . htmlspecialchars($Category['Product_name'][$i]) . '</a></li>';
        }
    }

    $output .= '
            </ul>
        </div>
    </div>';      
}

echo $output;

?>