[英]php merge/push array into other array
I just cannot get this fairly simple thing right. 我只是无法正确地解决这个问题。
I create many arrays like this: 我创建了许多这样的数组:
foreach( $terms as $term ){
$single_attribute = array();
$archive_link = get_term_link( $term->slug, $attribute['name'] );
array_push( $single_attribute, $term->name, $archive_link);
}
Which generates many arrays like following: 生成许多如下数组:
Array ( [0] => attribute_1 [1] => http://domain.com/products/attribute_1/ )
I need to push/merge (not sure about correct naming here) each of these arrays into one big array, so that the final result would be liek following: 我需要将每个数组推入/合并(不确定此处是否正确命名)到一个大数组中,以便最终结果如下:
Array ( [0] => Array ( [0] => attribute_1 [1] => http://domain.com/products/attribute_1 ) [1] => Array ( [0] => attribute_2 [1] => http://domain.com/products/attribute_2 ))
$single_attribute
is getting defined in every iteration with empty array. $single_attribute
在每次迭代中都使用空数组进行定义。 Define the array outside the loop. 在循环外定义数组。
$single_attribute = array();
foreach( $terms as $term ){
$archive_link = get_term_link( $term->slug, $attribute['name'] );
array_push( $single_attribute, array($term->name, $archive_link) );
}
A more elegant solution without using array_push
would be: 一个不使用array_push
更优雅的解决方案是:
foreach( $terms as $term ){
$archive_link = get_term_link( $term->slug, $attribute['name'] );
$single_attribute[] = array($term->name, $archive_link) );
}
$final_array[] = $single_attribute;
Which would give you your expected output. 这将为您提供预期的输出。
According to the documentation , you shouldn't use array_push()
for this task: 根据文档 ,您不应为此任务使用array_push()
:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function. 注意:如果使用array_push()将一个元素添加到数组中,则最好使用$ array [] =,因为这样可以节省调用函数的开销。
Do something like this: 做这样的事情:
$attributes = array();
foreach($terms as $term) {
$archive_link = get_term_link($term->slug, $attribute['name']);
$attributes[] = array($term->name, $archive_link);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.