0

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

3 Answers 3

2

$single_attribute is getting defined in every iteration with empty array. 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) );                                                                                      
}
Sign up to request clarification or add additional context in comments.

Comments

1

A more elegant solution without using array_push would be:

    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.

Comments

0

According to the documentation, you shouldn't use array_push() for this task:

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.