函数在多维数组中搜索值

时间:2017-08-26 06:03:23

标签: php arrays multidimensional-array

我得到了第一个(主要)数组,如下所示,

$groceritems = array(
        "apple" => array(
                "price"=>"10",
                "origin"=>array("australia","belgium","USA","canada"),
                "breed"=>array("gala","fuji","Honeycrisp","washington"),),

        "orange" => array(
                "price"=>"10",
                "origin"=>array("australia","belgium","USA","canada"),
                "breed"=>array("gala","fuji","Honeycrisp","washington"),

        ),
);
foreach ($groceritems as $key => $value) {
    $origins = $value['origin'];
    $breeds= $value['breed'];

    foreach (array_combine($origins, $breeds) as $origin=>$breed) { 

echo $breed ." ".$key." from ". $origin ." price is RM ". $value['price'];

        echo "<br>";    

    }


}

第二个数组如下,

$grocer= array(


"apple" => array( "country"=>"australia",
                  "newprice"=>"50",
                  "breed"=>"gala"),


"orange" => array("country"=>"belgium",
                  "newprice"=>"30",
                   "breed"=>"gala"),


);

我能够循环第一个数组但是如何将第一个数组的价格(在foreach循环中)替换为newprice,条件类别(orange / apple),country和breed匹配的第二个数组? 如下结果,

来自澳大利亚的嘎拉苹果价格为RM 50

来自比利时的富士苹果价格是RM 10

来自美国的Honeycrisp苹果价格为RM 10

来自加拿大的华盛顿苹果价格为RM 10

来自澳大利亚的gala orange价格为RM 10

来自比利时的富士橙价格为RM 10

来自美国的Honeycrisp橙色价格为RM 10

来自加拿大的华盛顿橙色价格为RM 10

1 个答案:

答案 0 :(得分:0)

要获得所需的结果,请执行以下操作

$groceritems = array(
    "apple" => array(
        "price"=>"10",
        "origin"=>array("australia","belgium","USA","canada"),
        "breed"=>array("gala","fuji","Honeycrisp","washington"),),

    "orange" => array(
        "price"=>"10",
        "origin"=>array("australia","belgium","USA","canada"),
        "breed"=>array("gala","fuji","Honeycrisp","washington"),

    ),
);

$grocer= array(
    "apple" => array( "country"=>"australia",
        "newprice"=>"50",
        "breed"=>"gala"),


    "orange" => array("country"=>"belgium",
        "newprice"=>"30",
        "breed"=>"gala"),
);

foreach ($groceritems as $key => $value) {
    $origins = $value['origin'];
    $breeds= $value['breed'];

    foreach (array_combine($origins, $breeds) as $origin=>$breed) {

        if(isset($grocer[$key]) && $origin == $grocer[$key]['country'] && $breed == $grocer[$key]['breed'] ){
            $price =  $grocer[$key]['newprice'];
        } else {
            $price = $value['price'];
        }

        echo $breed ." ".$key." from ". $origin ." price is RM ". $price;

        echo "<br>";

    }
}