gpt4 book ai didi

php - 按值从 mysql_query 结果过滤数组

转载 作者:行者123 更新时间:2023-11-29 12:02:35 25 4
gpt4 key购买 nike

所以...我是 PHP 傻瓜,我正在尝试过滤数组。

我有以下 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);
}

但它不起作用:(有什么想法吗?

最佳答案

正如评论所说,如果你在 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 horn],换句话说,你的 $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']));

关于php - 按值从 mysql_query 结果过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32127797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com