循环通过两个关联数组并添加值,如果找到针数组?

时间:2011-03-30 14:09:56

标签: php arrays foreach associative-array

我对以下功能有点困惑。目标是: - 循环通过一个包含所有产品的阵列 - 根据奢侈品与no_luxury划分产品 - 可用产品的另一种布局,我对可用产品有单独的功能,它返回一个关联数组。

我遇到的主要问题是我无法解析availableProducts数组中的价格值(以及所有其他值)。我想我需要将$ available_roducts关联数组的相应$值添加到$ no_luxury和$ luxury数组中,或从数组$ availableProducts中获取= $ value ['productType']的关联值

或许我可以合并两个数组?

这是我简化的PHP代码

<?php
$staticData = getStaticData();
$availableProducts = getAvailableProducts();

function getAllProductTypes($availableProducts, $staticData) {

    $allProductsTypes = array();
    $luxury = array();
    $no_luxury = array();

    $no_luxury_products = array('CALL','DODO','PKK','YTK','TK');
    //available products other layout with price and buy now button
    $available = array();
    //temp array for available products
    foreach($availableProducts as $value ){
        $available[] = $value['productType'];
        //HOW TO STORE an assoc array 
    }
    //get all products has no price value 
    $allProducts = getAllProducts();

     foreach ($allProducts as $value) {
        if(in_array($value["productType"], $no_luxury_products)){
            $no_luxury[] = $value;
        } else {
            $luxury[] = $value;
        }
    }
    //div no luxury

    $return = '<div id="no_luxury" style="background-color:#0099FF;">';

    foreach ($no_luxury as $value) {
        //and productType is not availabe
        if(!in_array($value['RoomType'],$available)){ 
                $return .= 'test'.$value['productType'].': '.$value['productDescr'];
        }//end not available
        else {//products ara available we have a price
                //problem i need to get the $value from the $availableProducts assoc array
                $return .= 'Price from $availableProducts assoc Array '.$value['productPrice'].': '.$value['productDescr'].' by '.$staticData['owner'];
        }
    }
    $return .= '</div>';
    //end no luxury

    //div luxury
    $return .= '<div id="luxury" >';
    foreach ($luxury as $value) {
        //and productType is not availabe
         if(!in_array($value['RoomType'],$available)){ 
                $return .= 'test'.$value['productType'].': '.$value['productDescr'];
         }//end not available
         else {//products ara available we have a price
            //problem i need to get the $value from the $availableProducts assoc array
              $return .= 'Price from $availableProducts assoc Array '.$value['productPrice'].': '.$value['productDescr'].' by '.$staticData['owner'];
         }
    }

    $return .= '</div>';
    return $return;
}

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您可以使用foreach($array as $key => $value )在循环数组时获取密钥。

此外,array_diff()array_intersect()也可能对您有帮助。