繁体   English   中英

函数中的Foreach循环仅返回数组中的最后一项

[英]Foreach loop in function only returns last item in array

我在下面的PHP代码遇到问题。 我正在尝试使用下面的函数来返回每个项目的UPC和imageURL。 当我在循环后print_r结果时,我收到了这个。

Array
(
    [upc] => 043396066731
    [ImageURL] => http://ecx.images-amazon.com/images/I/51HKXNNT53L._SL200_.jpg
)
Array
(
    [upc] => 096009394097
    [ImageURL] => http://ecx.images-amazon.com/images/I/512NKNWC8EL._SL200_.jpg
)

但是,当我使用return result然后print_r我只收到最后一个响应。 为什么这样,我如何修复我的代码以接收这两个项的值? 我搜索了谷歌和其他Stackoverflow问题,可以找到类似的情况,但我仍然在苦苦挣扎。

Array
(
    [upc] => 096009394097
    [ImageURL] => http://ecx.images-amazon.com/images/I/512NKNWC8EL._SL200_.jpg
)

这是我的功能

 function invokeGetMatchingProductForId(MarketplaceWebServiceProducts_Interface $service, $request) 
      {
          // try {
                  $response = $service->getMatchingProductForId($request);

        $dom = new DOMDocument();
        $dom->loadXML($response->toXML());
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        $parsed_xml = simplexml_import_dom($dom);
        //print_r($parsed_xml);

        $Result = array();

          foreach($parsed_xml->GetMatchingProductForIdResult as $item ) 
          {          
               $status = $item->attributes()->status;
              if (stristr($status, "Success") == true)
              {
                $Result['upc'] = (string)$item->attributes()->Id;
                $Result['ImageURL'] = str_replace('SL75','SL200',$item->Products->Product->AttributeSets->children('ns2', true)->ItemAttributes->SmallImage->URL);
              }  else {

                          $Result['upc'] = (string)$item->attributes()->Id;
                          $Result['ImageURL'] = "";
                      }
          }         
        print_r($Result);
}
// return $Result;
// }

// $amazonResult =invokeGetMatchingProductForId($service, $request);



// print_r($amazonResult);

您需要为阵列分配第二个键:

$Result['upc'][] = ;
$Result['ImageURL'][] = ;
                    ^-----

目前,每次分配新值时,您都要重置此$Result['upc']

根据您的要求,您需要创建二维数组

像这样使用foreach

foreach($parsed_xml->GetMatchingProductForIdResult as $item ) 
{          
     $status = $item->attributes()->status;
     if (stristr($status, "Success") == true)
     {
         $Result[]['upc'] = (string)$item->attributes()->Id;
         $Result[]['ImageURL'] = str_replace('SL75','SL200',$item->Products->Product->AttributeSets->children('ns2', true)->ItemAttributes->SmallImage->URL);
     }
     else 
     {
          $Result[]['upc'] = (string)$item->attributes()->Id;
          $Result[]['ImageURL'] = "";
     }
}         
print_r($Result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM