user1469270
user1469270

Reputation:

Loop through array within a multidimensional array

Here is my function that retrieves an array of paragraphs:

    function first_paragraph() {
      global $post, $posts;
      $first_para = '';
      ob_start();
      ob_end_clean();
      $post_content = $post->post_content;
      $post_content = apply_filters('the_content', $post_content);
      $output = preg_match_all('%(<p[^>]*>.*?</p>)%i', $post_content, $matches);
      $first_para = $matches[0][0];
      print_r($matches);
}

Which results in the following array:

(
    [0] => Array
        (
            [0] => <p>I am not in any category.</p>
            [1] => <p>Second paragraph.</p>
            [2] => <p>Third paragraph</p>
            [3] => <p>Fourth paragraph</p>
        )

    [1] => Array
        (
            [0] => <p>I am not in any category.</p>
            [1] => <p>Second paragraph.</p>
            [2] => <p>Third paragraph</p>
            [3] => <p>Fourth paragraph</p>
        )

)

Is it possible to loop through only one of these arrays, rather than both? I am new to PHP, so any guidance or resources would be appreciated.

PS: I'm not sure why preg_match_all returns two arrays, maybe someone can shed some light on that?

Upvotes: 0

Views: 72

Answers (2)

RAMe0
RAMe0

Reputation: 1257

I assume, that your post data looks like that:

<p>I am not in any category.</p>
<p>Second paragraph.</p>
<p>Third paragraph</p>
<p>Fourth paragraph</p>

So, according to PHP.net, by default $flags parameter is equal to PREG_PATTERN_ORDER, so "Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on."

So, for example, if you will change your patter to %<p[^>]*>(.*?)</p>%i, you woll get somthing like that:

(
    [0] => Array
        (
            [0] => <p>I am not in any category.</p>
            [1] => <p>Second paragraph.</p>
            [2] => <p>Third paragraph</p>
            [3] => <p>Fourth paragraph</p>
        )

    [1] => Array
        (
            [0] => I am not in any category.
            [1] => Second paragraph.
            [2] => Third paragraph
            [3] => Fourth paragraph
        )

)

So, if you need only subpatterns, you have to loop only throw subpattern results array. I assume that in your case it will be the second one ($matches[1]).

Read more about preg_match_all at PHP.net: http://php.net/manual/en/function.preg-match-all.php

Upvotes: 0

Gokan
Gokan

Reputation: 7

Yes you can doing this :

foreach ($matches as $key => $paragraph){
    if( $key == 0 ) {
        // Here you can use the value of $paragraph
        // $paragraph[0] contains "<p>I am not in any category.</p>"
        // $paragraph[1] contains "<p>Second paragraph.</p>"
        etc...
    }
}

Upvotes: 0

Related Questions