所以......我是PHP dummie,我正在尝试过滤数组。
我有以下php函数从MYSQL中检索数据
function hook_plan1($vars){
$result = mysql_query("SELECT * FROM tblpricing WHERE relid=12 AND type='product'");
$products = array();
while( $data = mysql_fetch_assoc($result)){
array_push($products, $data);
}
return array(
"plan1" => $products);
}
该函数呈现以下数组:
->plan1 = Array (7)
0 => Array (16)
id => "71"
type => "product"
currency => "1"
...
1 => Array (16)
id => "80"
type => "product"
currency => "3"
...
2 => Array (16)
id => "402"
type => "product"
currency => "14"
...
我想用“货币”(来自$ _SESSION)过滤那个数组,所以我可以得到一个单一的数组,如下所示:
->plan1 = Array (16)
id => "402"
type => "product"
currency => "14"
...
我很确定它很简单,所以我尝试了以下数组过滤器:
function hook_plan1($vars){
$currency_id = $_SESSION['currency'];//this is a number
$result = mysql_query("SELECT * FROM tblpricing WHERE relid=12 AND type='product'");
while ($data = mysql_fetch_assoc($result)) {
$products = $data;
}
$filter = (is_array($products) && $products['currency'] == $currency_id);
$filtered_product = (array_filter($products, $filter));
return array(
"plan1" => $filtered_product);
}
但它不起作用:( 有什么想法吗?
答案 0 :(得分:1)
正如评论所说,如果你在mysql查询中过滤它会好很多:
$currency_id = (int)$_SESSION['currency'];//you should be REALLY sure this is a number
$result = mysql_query("SELECT * FROM tblpricing WHERE relid=12 AND type='product' AND currency=$currency_id");
但是如果由于某种原因你肯定,绝对,肯定需要在PHP方面过滤它,那么你需要提供一个函数来返回一个函数[在这里插入Inception喇叭],换句话说你的$filter
变量应该是:
$filter = function($currencyToFilter) {
return function($arrayRow) use ($currencyToFilter) {
return $arrayRow['type'] === $currencyToFilter;
};
};
那是Closure thingy。然后你打电话(注意我使用$products
而不是$data
):
$filtered_product = array_filter($products, $filter($_SESSION['currency']));