2

I'm using Wordpress and I got 2 queries. One query is featured posts and the other is pulling standard posts. I'd like to replicate something similar to https://www.coolworks.com/winter-jobs. But theyre doing groups of 4. I'd like to do groups of 3.

So I'd like to show 3 featured posts, then 3 standard posts then repeat. How can I merge these arrays in php so they achieve my order?

$a1 = ['standard_1', 'standard_2', 'standard_3', 'standard_4', 'standard_5', 'standard_6', 'standard_7', 'standard_8', 'standard_9', 'standard_10'];
$a2 = ['featured_1', 'featured_2', 'featured_3', 'featured_4', 'featured_5', 'featured_6', 'featured_7', 'featured_8', 'featured_9', 'featured_10'];

// how do i get this order?

featured_1
featured_2
featured_3

standard_1
standard_2
standard_3

featured_4
featured_5
featured_6

standard_4
standard_5
standard_6

featured_7
featured_8
featured_9

standard_7
standard_8
standard_9

featured_10

standard_10
2
  • 1
    Are bothj arrays the same length? Commented Nov 24, 2017 at 16:32
  • Sounds like it might be worth looking into array_chunk(). Commented Nov 24, 2017 at 16:34

2 Answers 2

1

How about something like this?

    $combined = array();
    do {
        for ($x = 0 ; $x < 3; $x++){ 
            if ( count( $a2 ) ) {
                $combined[] = $a2[0];
                array_shift ( $a2 );
            }
        }

        for ($x = 0 ; $x < 3; $x++){ 
            if ( count( $a1 ) ) {
                $combined[] = $a1[0];
                array_shift ( $a1 );
            }
        }
    } while ( count( $a1 ) || count( $a2 ) );

This will result to:

Array
(
    [0] => featured_1
    [1] => featured_2
    [2] => featured_3
    [3] => standard_1
    [4] => standard_2
    [5] => standard_3
    [6] => featured_4
    [7] => featured_5
    [8] => featured_6
    [9] => standard_4
    [10] => standard_5
    [11] => standard_6
    [12] => featured_7
    [13] => featured_8
    [14] => featured_9
    [15] => standard_7
    [16] => standard_8
    [17] => standard_9
    [18] => featured_10
    [19] => standard_10
)
Sign up to request clarification or add additional context in comments.

Comments

1

I'd just iterate over both of them in groups of three:

$result = array();
$featured_index = 0;
$standard_index = 0;

while ($featured_index < count($featured) && $standard_index < count($standard)) {
    for ($i = 0; 
         $i < 3 && $featured_index < count($featured); 
         ++$i, ++$featured_index) {
        $result[] = $featured[$featured_index]; 
    }

    for ($i = 0;
         $i < 3 && $standard_index < count($standard); 
         ++$i, ++$standard_index) {
        $result[] = $standard[$standard_index]; 
    }
}

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.