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

时间:2014-11-29 12:33:23

标签: php arrays loops foreach

我试图通过foreach循环推送2D数组中的值,这样做会得到一些奇怪的结果。请看一下代码:

   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;
                    }
                }
              } 

通过print_r测试,我得到以下结果:

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

我想要的是:

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 个答案:

答案 0 :(得分:2)

只需对你的foreach做一个小改动即可。

foreach( $terms as $key => $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[$key]['name']  = $parent_term->name ;
            $term_list[$key]['slug'] = $parent_term->slug;
        }
    }
} 

你的

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

由重复的键组成,这些键将被其他

覆盖

更好的方法是将其作为

 Array
(
    [0] => Array
        (
            [name] =>  Category 2
            [slug] => category-2
        )

    [1] => Array
        (
            [name] =>  Category 3
            [slug] => category-3
        )
)

答案 1 :(得分:2)

因为没有人解释为什么它不起作用。

您对[]的使用不正确。你导致它创建另一个索引。尽管我会使用,但请参阅Barth的答案:

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

:)

答案 2 :(得分:1)

$term_list[] = ['name' => $parent_term->Name, 'slug' => $parent_term->slug];

是正确的方法。