从价值的mysql_query结果筛选数组 [英] filter an array from mysql_query result by value

查看:261
本文介绍了从价值的mysql_query结果筛选数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以...我是PHP dummie,我试图筛选数组。

So... I am PHP dummie and I am trying to filter an array.

我有以下PHP函数检索MYSQL数据

I have the following php function to retrieve data from 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)数组这样我就可以得到一个单一的阵列,像这样:

I would like to filter that array by "currency" (which comes in the $_SESSION) so I can get a single array, something like this:

->plan1 = Array (16)
    id => "402"
    type => "product"
    currency => "14"
    ...

我是pretty确保它是容易的,所以我尝试以下数组过滤器:

I was pretty sure it was easy, so I tried the following array filter:

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);
}

不过,这并不工作:(
任何想法?

But it doesn't work :( Any ideas?

推荐答案

随着评论说,如果你在MySQL查询过滤器这是好多了:

As the comments says, it's a lot better if you filter this in the mysql query:

$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端来过滤它,那么你需要提供一个返回函数的函数[此处插入初始角],换句话说,你的 $过滤器变量应该是:

$filter = function($currencyToFilter) {
        return function($arrayRow) use ($currencyToFilter) {
            return $arrayRow['type'] === $currencyToFilter;
        };
    };

这是一个封闭啄。然后调用(我使用 $产品而不是 $数据的通知

That's a Closure thingy. Then you call (notice that i use $products instead of $data):

$filtered_product = array_filter($products, $filter($_SESSION['currency']));

这篇关于从价值的mysql_query结果筛选数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆