dongxu1668 2016-01-30 22:02
浏览 65

在PHP中创建了foreach循环后,如何过滤数组?

I want to mention off the bat that although I am using some Wordpress specific PHP, the answer will not have anything to do with Wordpress. I have just added it to give the full code source.

I've written a "foreach loop" to "echo" ALL of the images i've uploaded in Wordpress' media library.

However I need to be able to select all the images in a certain folder. (i.e /thisfolder).



I just don't know how to say:

"if any of the values in the $imageURL begin with: http://localhost/testsite/wp-content/uploads/thisfolder/" then include them, else do not."

I tried to use substr() to filter it, but I cannot seem to find a way to get it to work. Any thoughts?

CODE:

<?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 />';
}

?>

RESULT:

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

I tried adding:

$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.....';
}
  • 写回答

2条回答 默认 最新

  • dsdvr06648 2016-01-30 22:06
    关注

    I would do something like

    $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 />';
       }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题