开发者

How to find an element in a structured array

The code below returns an array of images that are "attached" to posts...

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => 0
); 
$excludeImages = get_posts($args);

//var_dump

var_dump ($excludeImages)

//yields (a snippet of the first item of 5 in the array)

array(5){[0]=&开发者_运维知识库amp;gt; object(stdClass)#194 (24) 
        {["ID"]=> int(46) 
         ["guid"]=> string(59) "http://localhost/mysite/wp-content/uploads/avatar.png"}

The Question: How can I extract the image filename (in this case, avatar.png) from any given array item where the pattern is always ["guid"]=> string(int) "path-to-image"?


just use basename

$fileName = basename($excludeImages[0]->guid);

EDIT: As commenter above mentioned, i think you might need arrow notation instead of indexing for "guid" as in $excludeImages[0]["guid"]. I didn't notice initially that it is an object. It seems you have an array of objects, not a structured/nested array.

http://php.net/manual/en/function.basename.php
http://www.php.net/manual/en/function.pathinfo.php


stdClass is basically the default class for PHP (not the base!). It does not have any method or attribute, it's an empty class. It is used as a container. You can create such a class by casting an array to an object, for example.

Your var_dump means that the first element of your array is an stdClass object having a ID and guid attributes. Therefore, this code would retrieve the full guid :

$path = $excludeImages[0]->guid;

If you only want to retrieve the filename, you can use basename() :

echo basename($path); // avatar.png

You can see this question for more information about stdClass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜