Php 通过foreach创建数组

Php 通过foreach创建数组,php,Php,我正在使用SimpleXML从公共提要@Flickr中提取图像。我想将所有拉入的图像放入一个数组中,我已经这样做了: $images = array(); foreach($channel->item as $item){ $url = $path->to->url; $images[] = $url; } 从这里,我可以使用以下方法呼出所有图像: foreach($images as $image){ //output image } 然后,我决定

我正在使用SimpleXML从公共提要@Flickr中提取图像。我想将所有拉入的图像放入一个数组中,我已经这样做了:

$images = array();
foreach($channel->item as $item){
    $url = $path->to->url;
    $images[] = $url;
}
从这里,我可以使用以下方法呼出所有图像:

foreach($images as $image){
    //output image
}
然后,我决定既要有图像标题,也要有用户,因此我假设我会使用:

$images = array();
foreach($channel->item as $item){
    $url = $path->to->url;
    $title = $path->to->title;
    $images[$title] = $url;
}
我以为这意味着通过使用
$image['name of title']
我可以输出该标题的URL,但运行此操作时会出现非法偏移错误。。并且只有标题和url,但没有用户

在谷歌搜索了一段时间后,我发现你不能在数组键中使用
,但我尝试使用:

$normal = 'dddd';
$illegal = '  de___eee';
$li[$normal] = 'Normal';
$li[$illegal] = 'Illegal';
这输出正确,排除了数组键中的
是非法的(…我认为)

所以现在我真的很困惑为什么它不会运行,当我使用
print\r()
时,我注意到数组中有一些SimpleXML对象,这就是为什么我认为这是一个错误

理想的输出是以下格式的数组:

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

但我真的很困惑如何从
foreach
循环中形成这个,欢迎使用指向引用的链接以及其他问题(找不到任何问题)。

下划线不是数组键的禁止符号,这是您可能遇到的唯一问题,标题有时会重叠,您可能会丢失数组中的某些项。最正确的方法是

$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";
}

如果您喜欢关联数组,可以使用图像路径作为数组键,使用标题作为值。

下划线不是数组键的禁止符号,这是您可能遇到的唯一问题,标题有时会重叠,并且可能会丢失数组中的某些项。最正确的方法是

如果您喜欢关联数组,可以使用图像路径作为数组键,使用标题作为值