2010-04-07 81 views
3

我在PHP中创建了一个调用webservice并解析结果的函数,为变量赋值并将它们全部作为数组返回。这一切都完美的作品,但是我所遇到需要有在PHP函数中添加数组中的数组

我分配如下值“我的数组内数组”的:

$productName = $product->Name; 
$productID = $product->ID; 

$productArray = array(
      'productName' => "$productName", 
      'productID' => "$productID" 
      ); 

return $productArray; 

但是我现在有一个数据说回来有多个结果,所以我需要有一个额外的数组来存储这些,我使用foreach循环从返回的XML中获取值,但是我希望能够使用名称将它们添加到数组中,以便我可以引用它们返回的数据,这是我遇到问题的地方...

$bestForLists = $product->BestFors; 
     foreach($bestForLists as $bestForList) 
     { 
      $productBestFors = $bestForList->BestFor; 
      foreach($productBestFors as $productBestFor) 
       { 
        $productBestForName = $productBestFor->Name; 
        $productBestForID = $productBestFor->ID; 
       } 
     } 

我尝试使用下面的代码创建这些数组:

$bestForArray[] = (array(
       "productBestForID" => "$productBestForID", 
       "productBestForName" => "$productBestForName" 
       )); 

,然后在年底这些一起合并:

$productArray= array_merge($productArray,$bestForArray); 

如果我打印出来的返回值,我得到:

Array ([productName] => Test Product [productID] => 14128 [0] => Array ([productBestForID] => 56647 [productBestForName] => Lighting) [1] => Array ([productBestForID] => 56648 [productBestForName] => Sound))    

我想给内部数组一个名字,以便我可以在我的代码中引用它,或者有更好的方法来做到这一点,此刻我在我的PHP页面中使用以下内容来获取值:

$productName = $functionReturnedValues['productName']; 

我想用下面的访问数组然后我可以遍历:

$bestForArray = $functionReturnedValues['bestForArray']; 

希望有人能帮助

回答

3

你可以写

$productArray['bestForArray'] = $bestForArray; 

代替的

$productArray= array_merge($productArray,$bestForArray); 

告诉我,这是否有窍门! 杰罗姆·瓦格纳

+0

完美,没想到会那么简单!谢谢 – 2010-04-07 10:49:41