以下功能旨在获取.csv文件,读取一列并将其值转换为数组。然后,如果$category
(在本例中为“打印机”)出现在数组return "shipping-for-medium-sized-goods";
中。
function get_ship_class($category){
$csv = array_map("str_getcsv", file("https://siliconharvest.com.au/cassius-files/Shipping%20Classes.csv", "r"));
$header = array_shift($csv);
// Seperate the header from data
$col = array_search("medium_shipping_class", $header);
// Pass the extracted column back to calling method
return array_column($csv,$col);
if ( in_array( $category, get_ship_class() )) {
return "shipping-for-medium-sized-goods";
}
}
然后我运行该函数:
get_ship_class("printers");
// Note you can access the CSV file at that URL in the function above;
// See that"printers" is a value that occurs in the "medium_shipping_class" column
// Therefore we have a match for if ( in_array( $category = "printers", get_ship_class() ))
但是, 我收到错误消息:
警告:file()期望参数2为整数,字符串为 /home/ptrcao/public_html/siliconharvest/wp-content/uploads/wpallimport/functions.php 在第147行
警告:array_map():参数2应该是以下位置的数组 /home/ptrcao/public_html/siliconharvest/wp-content/uploads/wpallimport/functions.php 在第147行
警告:array_shift()期望参数1为数组,在中给出null /home/ptrcao/public_html/siliconharvest/wp-content/uploads/wpallimport/functions.php 在第148行
警告:array_search()期望参数2为数组,在中给出null /home/ptrcao/public_html/siliconharvest/wp-content/uploads/wpallimport/functions.php 在第151行
警告:array_column()期望参数1为数组,在中给出null /home/ptrcao/public_html/siliconharvest/wp-content/uploads/wpallimport/functions.php 在第154行
答案 0 :(得分:1)
正如@ Maio290所说,错误非常明显:
您正在使用字符串"r"
而不是整数作为第二个参数:
http://php.net/manual/en/function.file.php
标志
您需要一个整数或以下常量之一:
FILE_USE_INCLUDE_PATH
在include_path中搜索文件。我认为这是1
。
FILE_IGNORE_NEW_LINES
在每个数组元素的末尾省略换行符,我认为这是2
。
FILE_SKIP_EMPTY_LINES
跳过空行。我认为这是3
。
解决该问题很可能会解决其他错误,但是如果不能解决,或者有任何问题,请告诉我,我们将尽最大努力扩大回答以帮助您。
答案 1 :(得分:1)
<?php
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
function get_ship_class($category){
$csv = array_map("str_getcsv", file("https://siliconharvest.com.au/cassius-files/Shipping%20Classes.csv"));
$header = array_shift($csv);
// Seperate the header from data
if(in_array( "medium_shipping_class" ,$header)){
$col = array_search("medium_shipping_class" ,$header);
if($col = 'false'){
$col = '0';
}
}
// Pass the extracted column back to calling method
return array_column($csv,$col);
}
print_r(get_ship_class('printers'));
乍看起来似乎比较容易,但是布尔值存在此问题。所以让我解释一下。除了文件问题之外,您将字符串作为第二个参数(不知道为什么这样做)继续前进,您会遇到$col
的问题。由于您的元素位于数组0的第一位置,因此将转换为false
(布尔值)。因此,我要做的是先解决一下问题,首先确保要查找的值在数组中,并在得到它的位置后确定是否为假,然后将其转换为0。
if ( in_array( $category, get_ship_class() )) {
return "shipping-for-medium-sized-goods";
}
我刚刚将其取出的那部分是任何方式都无法达到的。它是在您返回后到达的,因此您将永远无法到达那里。函数returns
的值,此后没有任何反应。考虑类似die();
的事物。更进一步的输出结果是这样的:
Array ( [0] => printers [1] => monitors [2] => cases )