将数组传递到in_array()

时间:2018-11-22 14:04:50

标签: php arrays

请考虑以下PHP:

function get_ship_class()
{
    $csv = array_map("str_getcsv", file("somefile.csv", "r")); 
    $header = array_shift($csv); 

    // Seperate the header from data
    $col = array_search("heavy_shipping_class", $header); 

    foreach ($csv as $row)
    {      
        $array[] = $row[$col]; 
    }
}

如何将上述函数产生的数组传递给

if( in_array() ){
    //code
}

2 个答案:

答案 0 :(得分:7)

一个略微缩写的版本,但与建议的相同之处是从该函数返回所需的数据,但使用array_column()提取数据...

function get_ship_class()
{
    $csv = array_map("str_getcsv", file("somefile.csv", "r")); 
    $header = array_shift($csv); 

    // Seperate the header from data
    $col = array_search("heavy_shipping_class", $header); 

    // Pass the extracted column back to calling method
    return array_column($csv,$col);
}

并使用它...

if ( in_array( "somevalue", get_ship_class() )) {
   //Process 
}

如果要多次使用此返回值,则可能需要将其存储在变量中,而不是直接将其传递到in_array()方法中。

答案 1 :(得分:1)

这是评论所暗示的答案。

function get_ship_class(){
    $array = array();
    $csv = array_map("str_getcsv", file("somefile.csv", "r")); 
    $header = array_shift($csv); 
    // Seperate the header from data    
    $col = array_search("heavy_shipping_class", $header); 
    foreach ($csv as $row) {      
    array_push($array, $row[$col]);
    // array_push($array, "$row[$col]"); // You may need it as a string instead.
    }
return $array;
}



if( in_array("whatever_you_are_looking_for", get_ship_class()) ){
//code
}