开发者

Creating an array via foreach

I'm using SimpleXML to ext开发者_如何学Cract images from a public feed @ Flickr. I want to put all pulled images into an array, which I've done:

$images = array();
foreach($channel->item as $item){
    $url = $path->to->url;
    $images[] = $url;
}

From this I can then echo out all the images using:

foreach($images as $image){
    //output image
}

I then decided I wanted to have the image title as well as the user so I assumed I would use:

$images = array();
foreach($channel->item as $item){
    $url = $path->to->url;
    $title = $path->to->title;
    $images[$title] = $url;
}

I thought this would mean by using $image['name of title'] I could output the URL for that title, but it gives an Illegal Offset Error when I run this.. and would only have the title and url, but not the user.

After Googling a bit I read you cannot use _ in the array key, but I tried using:

$normal = 'dddd';
$illegal = '  de___eee';
$li[$normal] = 'Normal';
$li[$illegal] = 'Illegal';

And this outputs right, ruling out _ is illegal in array keys (..I think).

So now I'm really confused why it won't run, when I've used print_r() when playing around I've noticed some SimpleXML objects in the array, which is why I assume this is giving an error.

The ideal output would be an array in the format:

$image = array( 0 => array('title'=>'title of image',
                           'user'=>'name of user',
                           'url' =>'url of image'),
                1 => array(....)
         );

But I'm really stumped how I'd form this from a foreach loop, links to reference as well as other questions (couldn't find any) are welcome.


$images = array();
foreach ($channel->item as $item){
    $images[] = array(
        'title' => $item->path->to->title,
        'url'   => $item->path->to->url
    );
}

foreach ($images as $image) {
    echo "Title: $image[title], URL: $image[url]\n";
}


Underscore is not forbidden symbol for array keys, the only problem you might run to, that titles some times overlap and you might loose some items in your array. Most correct way would be deceze example

If you prefer associative array you can use image path as array key and title as value.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜