foreach中的数组仅显示第一个数组

时间:2017-01-13 07:57:39

标签: php arrays wordpress foreach

我忙于foreach循环,但我找不到问题。 此代码仅显示第一个数组,并停止。问题来自foreach循环中的数组。

这是我的代码:

<?php 
$catarray = array();
$catslug = array();

while ( have_posts() ) : the_post();
    global $post;
    $terms = get_the_terms( $post->ID, 'product_cat' );

    foreach ($terms as $term) {
        $array2 = array (  
            'name' => $term->name,  
            'slug' => $term->slug,
            'id' => $term->term_id
        );

        $product_cat = $array2;
        //$product_cat = $term->name;
        break;
    }
    array_push( $catarray, $product_cat );
endwhile;

$categorielijst = array_unique($catarray);

echo '<pre>';
print_r($categorielijst);
echo '</pre>';

?>

结果是:

    Array
(
    [0] => Array
        (
            [name] => Salades
            [slug] => salades
            [id] => 67
        )

)

如果我改变了 $ product_cat = $ array2; 对于 $ product_cat = $ term-&gt; name;

比输出:

Array
(
    [0] => Salades
    [1] => Aardappels
    [3] => Diverse fruit
    [4] => Blad groentes
    [5] => Schulp sappen 100% fruit en groentes
    [8] => Groentes
    [11] => Uien
    [13] => Verse kruiden
    [19] => Dressings kiooms
    [25] => Appels
    [28] => Paddenstoelen
    [32] => Tomaten
    [34] => Bananen
    [35] => Citrus fruit
    [37] => Peren
    [49] => Verse sla
)

2 个答案:

答案 0 :(得分:1)

尝试按照以下步骤更改您的foreach:

foreach ($terms as $term) {

    $array2 = array (  
        'name' => $term->name,  
        'slug' => $term->slug,
        'id' => $term->term_id
    );





    $product_cat[] = $array2;
}

根据要求,输出应该是:

Array ( [0] => Array ( [name] => Salades [slug] => salades [id] => 67 ) [1] => Array ( [name] => Aardappels [slug] => aardappels [id] => 23 ) [3] => Array ( [name] => Diverse fruit [slug] => diverse-fruit [id] => 11 )

Break导致您在一次迭代后退出循环。如Sougata所述,除非您附加product_cat

,否则您将覆盖product_cat[]

更新:假设您要对数组进行排序,并且&#39; id&#39;是独一无二的:

foreach ($terms as $term) {

    // check if its set, if not add it!
    if(!isset($product_cat[$term->term_id])){
        $product_cat[$term->term_id] = array('name'=>$term->name, 'slug' => $term->slug);
    }

}

答案 1 :(得分:0)

只需删除

即可

break;

并放

array_push( $catarray, $product_cat );

进入foreach循环

$catarray = array();
while ( have_posts() ) : the_post();
    global $post;
    $terms = get_the_terms( $post->ID, 'product_cat' );

    foreach ($terms as $term) {
        $array2 = array (  
            'name' => $term->name,  
            'slug' => $term->slug,
            'id' => $term->term_id
        );

        array_push( $catarray, $array2 );
    }

endwhile;
$categorielijst = array_unique($catarray);

echo '<pre>';
print_r($categorielijst);
echo '</pre>';