PHP在多维关联数组中使用If-else

时间:2015-01-05 16:44:52

标签: php arrays if-statement multidimensional-array

我的多维关联数组:

$search_cookies = array( 
    "type_catalog"  => $type_array,
    "size_catalog"  => $size_array,
    "color_catalog" => $color_array,
    );

我需要这样做:

$search_cookies = array( 
    if(isset($type_array){
        "type_catalog"  => $type_array,
    }
    elseif(isset($size_array)){
        "size_catalog"  => $size_array,
    }
    elseif(isset($color_array)){
        "color_catalog"  => $color_array,
    }
    );

如果您认为必须采用其他方式,则以下是整个代码:

$first_array = array('t-1', 's-32', 't-2', 's-36');

function removeLetters($row){
    return preg_replace("/[^0-9,.]/", "", $row);
}

foreach($first_array as $row){
    $exp_key = explode('-', $row);
    if($exp_key[0] == 't'){
        $type_array[] = removeLetters($row);
    }
    if($exp_key[0] == 's'){
        $size_array[] = removeLetters($row);
    }
    if($exp_key[0] == 'c'){
        $color_array[] = removeLetters($row);
    }
}

$search_cookies = array( 
    "type_catalog"  => $type_array,
    "size_catalog"  => $size_array,
    "color_catalog" => $color_array,
    );

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

$search_cookies = array();
if(isset($type_array)){
    $search_cookies["type_catalog"]  = $type_array;
}
if(isset($size_array)){
    $search_cookies["size_catalog"]  = $size_array;
}
if(isset($color_array)){
    $search_cookies["color_catalog"] = $color_array;
}