【发布时间】:2017-01-13 07:57:39
【问题描述】:
我正忙于一个 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->名称;
比是输出:
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
)
【问题讨论】:
-
期望的结果是什么?
-
我想要的是:
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;这会跳出循环? -
添加到@atoms
$product_cat的值如果删除break,将在每个循环中被覆盖。应该是$product_cat[] = value。
标签: php arrays wordpress foreach