Reputation: 123
So... I am PHP dummie and I am trying to filter an array.
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);
}
That function renders the following array:
->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"
...
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"
...
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?
Upvotes: 0
Views: 2918
Reputation: 409
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");
but if for some reason you definitely, absolutely, positively NEED to filter it in the PHP side, then you need to deliver a function that returns a function [insert Inception horn here], in other words your $filter
variable should be:
$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']));
Upvotes: 1