dongyi2083 2014-11-29 12:33
浏览 59
已采纳

通过PHP中的循环在数组中推送值

I'm trying to push values in a 2D array through foreach loop, I get some strange results while doing so. Please take a look at the code:

   foreach( $terms as $term ) {
                if(is_parent_tax($term)==TRUE){
                 $parent_term = get_term( $term->term_id, $taxonomy_name );
                    if(!in_array($parent_term->name,$term_list)){
                    $term_list[]['name']  = $parent_term->name ;
                    $term_list[]['slug'] = $parent_term->slug;
                    }
                }
              } 

Through a print_r test, I get the following results:

Array ( [0] => Array ( [name] => Category 2 ) [1] => Array ( [slug] => category-2 ) [2] => Array ( [name] => Category 3 ) [3] => Array ( [slug] => category-3 ) [4] => Array ( [name] => Category 4 ) [5] => Array ( [slug] => category-4 ) [6] => Array ( [name] => Category 2 ) [7] => Array ( [slug] => category-2 ) [8] => Array ( [name] => Category 1 ) [9] => Array ( [slug] => category-1 ) )

What I want instead, is:

Array ( [0] => Array ( [name] => Category 2 ) [0] => Array ( [slug] => category-2 ) [1] => Array ( [name] => Category 3 ) [1] => Array ( [slug] => category-3 ) [2] => Array ( [name] => Category 4 ) [2] => Array ( [slug] => category-4 ) [3] => Array ( [name] => Category 2 ) [3] => Array ( [slug] => category-2 ) [4] => Array ( [name] => Category 1 ) [4] => Array ( [slug] => category-1 ) )
  • 写回答

3条回答 默认 最新

  • douping1581 2014-11-29 12:39
    关注

    Since no one explained why it didn't work.

    Your usage of [] is incorrect. You're causing it to create another index. See Barth's answer although I would be using:

    $term_list[] = array('name' => $parent_term->name, 'slug' => $parent_term->slug);
    

    :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化