【问题标题】:How do I filter an array after I've already created a foreach loop in PHP?在 PHP 中创建了 foreach 循环后,如何过滤数组?
【发布时间】:2016-01-30 22:02:06
【问题描述】:

我想提一下,虽然我使用的是一些 Wordpress 特定的 PHP,但答案与 Wordpress 没有任何关系。我刚刚添加它以提供完整的代码源。

我已经编写了一个“foreach 循环”来“回显”我上传到 Wordpress 媒体库中的所有图像。

但是我需要能够选择某个文件夹中的所有图像。 (即 /thisfolder)。



我就是不知道怎么说:

"如果 $imageURL 中的任何值以: http://localhost/testsite/wp-content/uploads/thisfolder/" 然后包括 他们,否则不要。”

我尝试使用 substr() 来过滤它,但我似乎找不到让它工作的方法。有什么想法吗?

代码:

<?php

$query_images_args = array(
'post_type'      => 'attachment',
'post_mime_type' => 'image',
'post_status'    => 'inherit',
'posts_per_page' => - 1,
);

$query_images = new WP_Query( $query_images_args );

$images = array();
foreach ( $query_images->posts as $image ) {
$images[] = wp_get_attachment_url( $image->ID );
}

for($i = 0; $i < count($images); $i++) {
$imageURL = $images[$i];

echo $imageURL . '<br /><br />';
}

?>

结果:

http://localhost/testsite/wp-content/uploads/thisfolder/01.jpg

http://localhost/testsite/wp-content/uploads/thisfolder/02.jpg

http://localhost/testsite/wp-content/uploads/2016/01/03.jpg

http://localhost/testsite/wp-content/uploads/2016/01/04.jpg

我尝试添加:

$URLlength = 'http://localhost/testsite/wp-content/uploads/thisfolder';

$akumalURL = substr( $URLlength, 0, strlen($URLlength)) === $URLlength;

if (in_array($akumalURL, $imageURL)) {
echo 'sucess!';
}
else {
echo 'bummer.....';
}

【问题讨论】:

    标签: php wordpress image foreach


    【解决方案1】:

    我会做类似的事情

    $URLlength = 'http://localhost/testsite/wp-content/uploads/thisfolder';
    for($i = 0; $i < count($images); $i++) {$imageURL = $images[$i];
       if(strpos($imageURL, $URLlength) === 0){
          echo $imageURL . '<br /><br />';
       }
    }
    

    【讨论】:

      【解决方案2】:

      你可以这样做,

      for($i = 0; $i < count($images); $i++) {
          $imageURL = $images[$i];
          if ( strpos(  $imageURL, 'thisfolder') !== false ) {
              echo $imageURL . '<br /><br />';
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-05-01
        • 2014-02-13
        • 2018-01-14
        • 2018-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多