php从数组中提取值并传递给函数作为参数

时间:2016-12-23 10:15:04

标签: php arrays extract

如何提取[p_id]值并在函数中作为参数传递?

Array
(
    [0] => Array
        (
            [p_name] => X-Dot Motorbike Helmet
            [p_id] => 1001
            [p_price] =>  1.60
            [p_alt-variation-1] => Red
        )

    [1] => Array
        (
            [p_name] => Salt and Lemon Candy
            [p_id] => 1002
            [p_price] => 1.20
        )

    [2] => Array
        (
            [p_name] => Romoss Rolink Hybrid Cable
            [p_id] => 1003
            [p_price] => 13.90
        )

)
例如,我需要将这些id传递给SQL语句的函数:

function process($ids = array('1001','1002','1003')) {

    $sql = "SELECT * FROM tbl WHERE pid IN('1001','1002','1003') GROUP BY categoryId";

    ...

}

4 个答案:

答案 0 :(得分:2)

使用array_map()将所有ID转换为$ ids数组:

   $ids = array_map(function($v){return $v[p_id];}, $array);

然后你可以传递$ ids数组作为你函数的参数。

答案 1 :(得分:2)

假设$array是你的二维数组,循环它并将所有ID添加到另一个数组,并将其作为参数传递

$ids = array(); // Declare array which will contain IDs
foreach ($array as $value) {
    // Loop over array, and get the IDs, put it into your $ids array
    $ids[] = $value['p_id'];
}

// Pass it as an argument
process($ids);

然后,您需要调整查询,因为它目前是静态的。使用implode()将数组转换为字符串,如此

function process($ids = array() {
    $sql = "SELECT * FROM tbl WHERE pid IN('".implode("', '", $ids)."') GROUP BY categoryId";

    ...
}

答案 2 :(得分:1)

使用array_columnimplode函数的解决方案:

// $data is your initial array
$ids = array_column($data, 'p_id');

function process($ids = []) {
    if (!empty($ids)) {
        $sql = "SELECT * FROM tbl WHERE pid IN(".implode(", ", $ids).") GROUP BY categoryId";
    } 

    ...

}

答案 3 :(得分:1)

  1. 首先使用array_column(即:http://php.net/manual/en/function.array-column.php

    从p_id中提取值
    $value = array_column($array, 'p_id');
    
  2. 然后你可以将$值传递给你的函数

    process($value);
    
  3. 在将数组传递到sql

    之前,将数组内部压缩到函数中
    function process($value = array()) {
        $value = "'".implode("', '", $value)."'";
        $sql = "SELECT * FROM tbl WHERE pid IN({$value}) GROUP BY categoryId";
    }