PHP array_map变量作用域,如何将变量传递给array_map函数

时间:2019-05-08 00:16:52

标签: php variables scope array-map

我正在尝试通过传递定义货币汇率的url变量来修改CVS价格列表导出文件。

但是,如果我尝试将变量添加到array_map函数中,则表明该变量是未定义的,即使它们在作用域中设置得较高。

我没有构建此价目表导出文件,但是开发人员目前无法提供帮助,因此我们将不胜感激。

请参阅以下带有注释的代码...

如果您在代码下面阅读了我的评论,可能会使问题更容易理解。

// this is my common function class to get url variable
$sCurrency = CF::getVar('currency');

// this is my exchange rate from my site settings
$iEuro = (int)get_field('currency_rate_eur','option');

// get our posts
$posts = get_posts([
    'post_type' => 'product'
]);

// create empty array of data
$data = [];

// loop through our posts
foreach ($posts as $post) {

    $data[$post->ID] = [
        'quantities' => get_field('product_prices', $post_id)
    ];

}

// format our quantities for every item
{

    // more code here but not included for this question

    // map our data to include our structured quantities
    $data = array_map(function ($row) use ($quantities) {

        // more code here but not included for this question

        // combine all of our values
        $row['quantities'] = array_combine(
            array_map(function ($row) {
                return $row['quantity'];
            }, $row['quantities']),
            array_map(function ($row) {
                return $row['unit_price'];
            }, $row['quantities'])
        );

        return $row;

    }, $data);
}

在上面的代码中,您将看到其中包含array_map函数的组合数组函数。

我正在尝试将变量传递给返回array_map的{​​{1}}。

因此,我可以将$row['unit_price']乘以定义汇率的url变量。

但是每次我尝试在array_map函数中使用变量时,都会收到一条错误消息,指出var未定义。

这是我在下面的尝试,但是不断出现不确定的变量错误...

$row['unit_price']

我知道我需要列出这些返回的值,但是我想知道为什么array_map(function ($row) { // set unit price var $iUnitPrice = $row['unit_price']; // if currency var is defined as euro if($sCurrency === 'eur') { // then multiply the unit price by the euro exchange rate $iUnitPrice = $iUnitPrice * $iEuro; } // return the appropriate unit price return $iUnitPrice; }, $row['quantities']) 从范围中排除这些变量。

谢谢。

0 个答案:

没有答案