2015-08-20 34 views
0

所以...我是PHP dummie,我试图过滤一个数组。从mysql_query结果过滤数组值

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

你为什么不只是添加到查询了'WHERE'条款? – Barmar

+0

'AND currency ='$ currency_id'' – Barmar

+0

1)你的'$ filter'不是一个函数,它应该是; 2)你试图过滤'$ data',而不是'$ products'。 – raina77ow

回答

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端对其进行过滤,然后你需要交付[在此插入盗喇叭]返回函数的函数,换句话说,你$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'])); 
+0

请*先*退出'$ currency_id',然后再将它连接到'$ result'。一个人永远不能确定。 – rlanvin

+1

除了铸造它(正如我上面编辑)和使用PDO,是否有其他方法来逃避一个数字? –

+1

有几个:[mysql_real_escape_string](http://php.net/manual/en/function.mysql-real-escape-string.php)(不建议使用),[mysqli_real_escape_string](http://php.net/manual /en/mysqli.real-escape-string.php),或者对于数字来说,旧的'sprintf('%d')'(例如'$ query = sprintf('SELECT [...] AND currency_id =% d”,$ currency_id);')。 PDO是最好的。 – rlanvin