dtu1747 2017-01-13 07:57
浏览 141
已采纳

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

I am busy with a foreach loop but i can't find the problem. This code show only first array, and stops. The problem comes from the array in the foreach loop.

Here is my code:

<?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>';

?>

The result is:

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

)

And if i change $product_cat = $array2; for $product_cat = $term->name;

Than is the output:

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条回答 默认 最新

  • douxia3505 2017-01-13 08:19
    关注

    Try changing your foreach to work as followed:

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

    As requested, the output should be something like:

    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 was causing you to exit the loop after one iteration. And as mentioned by Sougata you would be overwriting product_cat unless you append it with product_cat[]

    UPDATE: Assuming that you want to sort arrays and 'id' is unique:

    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条)

报告相同问题?

悬赏问题

  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!