0

我使用 Zend Framework 2。我使用 AJAX 从服务器获取数据,以及如何使用 JSON 返回格式化数据。(例如,.phtml 文件 $this->currencyFormat(1234.56, "TRY", "tr_TR") 中的多货币格式)我不能从操作中使用视图助手。

我的代码是这样的。(MyController.php)

<?php
class MyController extends AbstractActionController
{
    public function myAction(){
        $data = array();
        //i want to format this data for multi currency format. as us,fr,tr etc..
        $data['amount'] = '100'; 

        return new JsonModel(data);
    }

}
4

2 回答 2

1

Yargicx,感谢您提出这个问题。它使我了解了 PHP (5.3) 的一个新特性。这是返回原始问题答案的代码:JSON 格式的货币。如果您不熟悉可调用类,它可能看起来有点奇怪,但我会解释它是如何工作的。

use Zend\I18n\View\Helper\CurrencyFormat;
use Zend\View\Model\JsonModel;

class MyController extends AbstractActionController
{
    public function myAction()
    {
        $data = array();
        //i want to format this data for multi currency format. as us,fr,tr etc..
        $currencyFormatter = new CurrencyFormat();
        $data['amount'] = $currencyFormatter(1234.56, "TRY", "tr_TR");

        return new JsonModel($data);
    }
}

为了达到这一点,我查看了类中的currencyFormat()方法Zend\I18n\View\Helper\CurrencyFormat并注意到这是一个受保护的方法,因此我不能直接在控制器操作中使用它。

然后我注意到有一个神奇的__invoke()方法(以前从未见过)我在http://www.php.net/manual/en/language.oop5.magic.php#object 上查找了它的 PHP 文档。调用. 事实证明,您可以像使用如下函数一样使用对象。注意最后一行:

class Guy
{
    public function __invoke($a, $b)
    {
        return $a + $b;
    }
}

$guy = new Guy();
$result = $guy();

由于类的__invoke()方法Zend\I18n\View\Helper\CurrencyFormat返回的是对该currencyFormat()方法的调用结果,所以我们可以用与方法相同的参数来调用类currencyFormat(),从而得到这个答案中的原始代码块。

为了踢球,这是该类__invoke()函数的源代码:Zend\I18n\View\Helper\CurrencyFormat

public function __invoke(
    $number,
    $currencyCode = null,
    $showDecimals = null,
    $locale       = null,
    $pattern      = null
) {
    if (null === $locale) {
        $locale = $this->getLocale();
    }
    if (null === $currencyCode) {
        $currencyCode = $this->getCurrencyCode();
    }
    if (null === $showDecimals) {
        $showDecimals = $this->shouldShowDecimals();
    }
    if (null === $pattern) {
        $pattern = $this->getCurrencyPattern();
    }

    return $this->formatCurrency($number, $currencyCode, $showDecimals, $locale, $pattern);
}
于 2014-03-24T05:56:13.950 回答
0

尝试

return new JsonModel('data' => $data);

其他一切都应该工作

编辑

$jsonencoded = \Zend\Json\Json::encode($data);//json string

$jsondecode = \Zend\Json\Json::decode($jsonencoded, \Zend\Json\Json::TYPE_ARRAY);

http://framework.zend.com/manual/2.0/en/modules/zend.json.objects.html

这就是你的意思?

于 2014-03-20T07:37:09.810 回答