在多维数组中循环遍历数组

时间:2014-01-13 22:17:46

标签: php arrays multidimensional-array

这是我的函数,它检索段落数组:

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

这导致以下数组:

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

)

是否可以只遍历其中一个阵列,而不是两者?我是PHP的新手,所以任何指导或资源都会受到赞赏。

PS:我不确定为什么preg_match_all会返回两个数组,也许有人可以对此有所了解?

2 个答案:

答案 0 :(得分:0)

是的,你可以这样做:

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...
    }
}

答案 1 :(得分:0)

我认为您的帖子数据看起来像是:

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

因此,根据PHP.net,默认情况下$ flags参数等于 PREG_PATTERN_ORDER ,因此“Orders结果使得 $ matches [0]是一个完整模式匹配的数组< / strong>,$ matches [1]是由第一个带括号的子模式匹配的字符串数组,依此类推。“

所以,例如,如果你将你的模式改为%<p[^>]*>(.*?)</p>%i,你会得到类似的东西:

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

)

因此,如果只需要子模式,则必须仅循环抛出子模式结果数组。我假设在你的情况下它将是第二个($ matches [1])。

在PHP.net上阅读有关preg_match_all的更多信息:http://php.net/manual/en/function.preg-match-all.php