当前位置: 首页>>代码示例>>PHP>>正文


PHP Json::encode方法代码示例

本文整理汇总了PHP中Zend\Json\Json::encode方法的典型用法代码示例。如果您正苦于以下问题:PHP Json::encode方法的具体用法?PHP Json::encode怎么用?PHP Json::encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Zend\Json\Json的用法示例。


在下文中一共展示了Json::encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: showAction

 /**
  * return geojson representation of test points given either
  *
  *  - neighborhood name and region name
  */
 public function showAction()
 {
     $neighborhood_name = $this->getRequestParameter('neighborhood');
     $region_name = $this->getRequestParameter('region');
     $grid_resolution = $this->getRequestParameter('grid-res');
     if (empty($neighborhood_name) or empty($region_name) or empty($grid_resolution)) {
         die("neighborhood_name,region_name and grid_res must all be defined");
     }
     $neighborhood = $this->m()->neighborhoodMapper()->byName($neighborhood_name, $region_name);
     if (empty($neighborhood)) {
         die("no neighborhood found");
     }
     $user_polygons = $this->m()->userPolygonMapper()->byNeighborhood($neighborhood);
     if (empty($user_polygons)) {
         die("no user polygons found for neighborhood");
     }
     $timer = \Whathood\Timer::start('api');
     $points = $this->m()->testPointMapper()->createByUserPolygons($user_polygons, $grid_resolution);
     $test_point_ms = $timer->elapsed_milliseconds();
     $test_point_count = count($points);
     $this->logger()->info(sprintf("generated %s test points in %sms; %sms per 1000 points", $test_point_count, $test_point_ms, round($test_point_ms / $test_point_count * 1000, 1)));
     if (empty($points)) {
         die("no points returned with grid_resolution {$grid_resolution}");
     }
     $timer = \Whathood\Timer::start('election');
     $consensus_col = $this->m()->electionMapper()->buildElectionPointCollection($points);
     $consensus_seconds = $timer->elapsed_seconds();
     $this->logger()->info(sprintf("got consensus in %s seconds; %sms per point", $consensus_seconds, round($consensus_seconds / count($points) * 1000, 2)));
     $timer = \Whathood\Timer::start('election');
     $consensus_col = $this->m()->electionMapper()->buildElectionPointCollection($points);
     $points = $consensus_col->pointsByNeighborhoodId($neighborhood->getId());
     \Zend\Debug\Debug::dump(get_class($points[0]));
     print Json::encode(\Whathood\Spatial\Util::multiPointToGeoJsonArray(new WhMultiPoint($points)));
 }
开发者ID:KGalley,项目名称:whathood,代码行数:39,代码来源:TestPointController.php

示例2: htmlAttribs

 /**
  * Converts an associative array to a string of tag attributes.
  *
  * @access public
  *
  * @param array $attribs From this array, each key-value pair is
  * converted to an attribute name and value.
  *
  * @return string The XHTML for the attributes.
  */
 protected function htmlAttribs($attribs)
 {
     $xhtml = '';
     $escaper = $this->getView()->plugin('escapehtml');
     foreach ((array) $attribs as $key => $val) {
         $key = $escaper($key);
         if ('on' == substr($key, 0, 2) || 'constraints' == $key) {
             // Don't escape event attributes; _do_ substitute double quotes with singles
             if (!is_scalar($val)) {
                 // non-scalar data should be cast to JSON first
                 $val = \Zend\Json\Json::encode($val);
             }
             // Escape single quotes inside event attribute values.
             // This will create html, where the attribute value has
             // single quotes around it, and escaped single quotes or
             // non-escaped double quotes inside of it
             $val = str_replace('\'', ''', $val);
         } else {
             if (is_array($val)) {
                 $val = implode(' ', $val);
             }
             $val = $escaper($val);
         }
         if ('id' == $key) {
             $val = $this->normalizeId($val);
         }
         if (strpos($val, '"') !== false) {
             $xhtml .= " {$key}='{$val}'";
         } else {
             $xhtml .= " {$key}=\"{$val}\"";
         }
     }
     return $xhtml;
 }
开发者ID:mindfeederllc,项目名称:openemr,代码行数:44,代码来源:AbstractHtmlElement.php

示例3: render

 /**
  * Render the view into a string and return for output
  *
  * @param mixed $input
  * @return string
  */
 public function render($input = null)
 {
     $output = (object) $this->template;
     if (isset($input["status"])) {
         $output->status = $input["status"];
     } else {
         unset($output->status);
     }
     if (isset($input["errors"])) {
         $output->errors = $input["errors"];
     } else {
         unset($output->errors);
     }
     if (isset($input["data"])) {
         $output->data = $input["data"];
     } else {
         unset($output->data);
     }
     if (isset($input["messages"])) {
         $output->messages = $input["messages"];
     } else {
         unset($output->messages);
     }
     return Json::encode($input);
 }
开发者ID:epoplive,项目名称:pillow,代码行数:31,代码来源:SimpleJSONTemplateView.php

示例4: callGa

 protected function callGa(array $params)
 {
     $jsArray = Json::encode($params);
     $jsArrayAsParams = substr($jsArray, 1, -1);
     $output = sprintf("\n" . '%s(%s);', $this->getFunctionName(), $jsArrayAsParams);
     return $output;
 }
开发者ID:riteshkmr33,项目名称:ovessnce,代码行数:7,代码来源:Analyticsjs.php

示例5: direct

    /**
     * Encode data as JSON, disable layouts, and set response header
     *
     * If $keepLayouts is true, does not disable layouts.
     *
     * @param  mixed $data
     * @param  bool $keepLayouts
     * NOTE:   if boolean, establish $keepLayouts to true|false
     *         if array, admit params for Zend_Json::encode as enableJsonExprFinder=>true|false
     *         this array can contains a 'keepLayout'=>true|false
     *         that will not be passed to Zend_Json::encode method but will be used here
     * @return string|void
     */
    public function direct($data = null, $keepLayouts = false)
    {
        if ($data == null) {
            throw new \InvalidArgumentException('JSON: missing argument. $data is required in json($data, $keepLayouts = false)');
        }
        
        $options = array();
        if (is_array($keepLayouts))
        {
            $options     = $keepLayouts;
            $keepLayouts = (array_key_exists('keepLayouts', $keepLayouts))
                            ? $keepLayouts['keepLayouts']
                            : false;
            unset($options['keepLayouts']);
        }

        $data = \Zend\Json\Json::encode($data, null, $options);
        if (!$keepLayouts) {
            $layout = LayoutManager::getMvcInstance();
            if ($layout instanceof LayoutManager) {
                $layout->disableLayout();
            }
        }

        $response = \Zend\Controller\Front::getInstance()->getResponse();
        $response->setHeader('Content-Type', 'application/json');
        return $data;
    }
开发者ID:niallmccrudden,项目名称:zf2,代码行数:41,代码来源:Json.php

示例6: validateAction

 /**
  * Validate a field and return validation messages on failure
  *
  * @throws \InvalidArgumentException
  * @return \Zend\Stdlib\ResponseInterface
  */
 public function validateAction()
 {
     /** @var $request \Zend\Http\PhpEnvironment\Request */
     $request = $this->getRequest();
     $response = $this->getResponse();
     $data = $request->getPost()->toArray();
     if (count($data) > 1) {
         throw new \InvalidArgumentException('Validating multiple fields is not allowed');
     }
     if (empty($data)) {
         throw new \InvalidArgumentException('No input data received');
     }
     $formAlias = $this->getEvent()->getRouteMatch()->getParam('form');
     /** @var $form \Zend\Form\FormInterface */
     $form = $this->getFormManager()->get($formAlias);
     $filter = $form->getInputFilter();
     $filter->setData($data);
     $filter->setValidationGroup($this->convertDataArrayToValidationGroup($data));
     $valid = $filter->isValid();
     if (!$valid) {
         $messages = $filter->getMessages();
         $result = false;
         array_walk_recursive($messages, function ($item) use(&$result) {
             if (is_string($item)) {
                 $result = $item;
             }
         });
     } else {
         $result = true;
     }
     $response->setContent(\Zend\Json\Json::encode($result));
     return $response;
 }
开发者ID:rettal,项目名称:zf2-form,代码行数:39,代码来源:AjaxController.php

示例7: notify

 /**
  * Defined by Zend\ProgressBar\Adapter\AbstractAdapter
  *
  * @param  float   $current       Current progress value
  * @param  float   $max           Max progress value
  * @param  float   $percent       Current percent value
  * @param  int $timeTaken     Taken time in seconds
  * @param  int $timeRemaining Remaining time in seconds
  * @param  string  $text          Status text
  * @return void
  */
 public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text)
 {
     $arguments = array('current' => $current, 'max' => $max, 'percent' => $percent * 100, 'timeTaken' => $timeTaken, 'timeRemaining' => $timeRemaining, 'text' => $text);
     $data = 'parent.' . $this->updateMethodName . '(' . Json::encode($arguments) . ');';
     // Output the data
     $this->_outputData($data);
 }
开发者ID:antarus,项目名称:mystra-pve,代码行数:18,代码来源:AjaxPush.php

示例8: arrayToJsonString

 public static function arrayToJsonString($aDane)
 {
     ob_start();
     echo \Zend\Json\Json::encode($aDane);
     $sOut = ob_get_clean();
     return $sOut;
 }
开发者ID:mariuszfilip,项目名称:umowatorium,代码行数:7,代码来源:Json.php

示例9: validatepostajaxAction

 public function validatepostajaxAction()
 {
     $form = $this->getForm();
     $request = $this->getRequest();
     $response = $this->getResponse();
     $messages = array();
     if ($request->isPost()) {
         $form->setData($request->getPost());
         $formValidador = new ValidaFormulario();
         $form->setInputFilter($formValidador->getInputFilter());
         echo "es valido2: " . "<pre>" . print_r($form->isValid(), true) . "</pre>";
         if (!$form->isValid()) {
             $errors = $form->getMessages();
             foreach ($errors as $key => $row) {
                 if (!empty($row) && $key != 'enviar') {
                     foreach ($row as $keyer => $rower) {
                         //save error(s) per-element that
                         //needed by Javascript
                         $messages[$key][] = $rower;
                     }
                 }
             }
         }
         if (!empty($messages)) {
             $response->setContent(\Zend\Json\Json::encode($messages));
         } else {
             //save to db <span class="wp-smiley wp-emoji wp-emoji-wink" title=";)">;)</span>
             echo "son válidos los datos";
             //$this->savetodb($form->getData());
             $response->setContent(\Zend\Json\Json::encode(array('success' => 1)));
         }
     }
     return $response;
 }
开发者ID:jialero,项目名称:sirSoftware,代码行数:34,代码来源:AjaxController.php

示例10: notify

 /**
  * Defined by Zend\ProgressBar\Adapter\AbstractAdapter
  *
  * @param  float   $current       Current progress value
  * @param  float   $max           Max progress value
  * @param  float   $percent       Current percent value
  * @param  int $timeTaken     Taken time in seconds
  * @param  int $timeRemaining Remaining time in seconds
  * @param  string  $text          Status text
  * @return void
  */
 public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text)
 {
     $arguments = ['current' => $current, 'max' => $max, 'percent' => $percent * 100, 'timeTaken' => $timeTaken, 'timeRemaining' => $timeRemaining, 'text' => $text];
     $data = '<script type="text/javascript">' . 'parent.' . $this->updateMethodName . '(' . Json::encode($arguments) . ');' . '</script>';
     // Output the data
     $this->_outputData($data);
 }
开发者ID:GeeH,项目名称:zend-progressbar,代码行数:18,代码来源:JsPush.php

示例11: dataAction

 public function dataAction()
 {
     $response = $this->getResponse();
     $grid = $this->grid('Application\\Index\\Index', array('-', 'id', 'title', 'category', 'username', 'created_at', '-'));
     if (isset($this->getSessionContainer()->parent_id)) {
         $grid['parent_id'] = $this->getSessionContainer()->parent_id;
     }
     $result = $this->getResourceTable()->fetchDataGrid($grid);
     $adapter = new ArrayAdapter($result);
     $paginator = new Paginator($adapter);
     $page = ceil(intval($grid['start']) / intval($grid['length'])) + 1;
     $paginator->setCurrentPageNumber($page);
     $paginator->setItemCountPerPage(intval($grid['length']));
     $data = array();
     $data['data'] = array();
     foreach ($paginator as $row) {
         $category = array_key_exists('category', $row) ? $row['category'] : '-';
         $title = $row['node_type'] == \Application\Model\Resource::NODE_TYPE_CATEGORY ? '<a href="/admin/resource/parent_id/' . $row['id'] . '" title="' . strip_tags($row['description']) . '">' . strip_tags($row['title']) . '</a>' : '<i>' . strip_tags($row['title']) . '</i>';
         $actions = '';
         if ($row['url']) {
             $actions .= '<a class="btn btn-xs btn-outline blue-steel btn-view" href="' . $row['url'] . '" data-id="' . $row['id'] . '" target="_blank">View</a>&nbsp;';
         }
         $actions .= '<a class="btn btn-xs btn-outline red" href="/admin/resource/delete/id/' . $row['id'] . '" onclick="return confirm("Are you sure you wish to delete selected resources?");">Delete</a>';
         $data['data'][] = array('<input type="checkbox" name="id[' . $row['id'] . ']" value="' . $row['id'] . '" />', '<a class="btn btn-xs btn-outline blue-steel btn-view" href="/admin/resource/edit/id/' . $row['id'] . '/parent_id/' . $row['parent_id'] . '" title="' . $row['id'] . '">Edit: ' . $row['id'] . '</a>', $title, $category, $row['username'], date('F jS Y', strtotime($row['created_at'])), $actions);
     }
     $data['page'] = $page;
     $data['grid'] = $grid;
     $data['draw'] = intval($grid['draw']);
     $data['recordsTotal'] = $paginator->getTotalItemCount();
     $data['recordsFiltered'] = $paginator->getTotalItemCount();
     $response->setStatusCode(200);
     $response->setContent(Json::encode($data));
     return $response;
 }
开发者ID:tomshaw,项目名称:resource-datastore,代码行数:34,代码来源:ResourceController.php

示例12: convertToDatabaseValue

 public function convertToDatabaseValue($value, AbstractPlatform $platform)
 {
     if (null === $value) {
         return null;
     }
     return Json::encode($value);
 }
开发者ID:MagmaDigitalLtd,项目名称:ZucchiDoctrine,代码行数:7,代码来源:ImageType.php

示例13: serialize

 /**
  * Override serialize()
  *
  * Tests for the special top-level variable "payload", set by ZF\Rest\RestController.
  *
  * If discovered, the value is pulled and used as the variables to serialize.
  *
  * A further check is done to see if we have a ZF\Hal\Entity or
  * ZF\Hal\Collection, and, if so, we pull the top-level entity or
  * collection and serialize that.
  *
  * @return string
  */
 public function serialize()
 {
     $variables = $this->getVariables();
     // 'payload' == payload for HAL representations
     if (isset($variables['payload'])) {
         $variables = $variables['payload'];
     }
     // Use ZF\Hal\Entity's composed entity
     if ($variables instanceof HalEntity) {
         $variables = method_exists($variables, 'getEntity') ? $variables->getEntity() : $variables->entity;
         // v1.0-1.1.*
     }
     // Use ZF\Hal\Collection's composed collection
     if ($variables instanceof HalCollection) {
         $variables = $variables->getCollection();
     }
     if (null !== $this->jsonpCallback) {
         return $this->jsonpCallback . '(' . Json::encode($variables) . ');';
     }
     $serialized = Json::encode($variables);
     if (false === $serialized) {
         $this->raiseError(json_last_error());
     }
     return $serialized;
 }
开发者ID:zfcampus,项目名称:zf-content-negotiation,代码行数:38,代码来源:JsonModel.php

示例14: testCanSerializeWithJsonpCallback

 public function testCanSerializeWithJsonpCallback()
 {
     $array = array('foo' => 'bar');
     $model = new JsonModel($array);
     $model->setJsonpCallback('callback');
     $this->assertEquals('callback(' . Json::encode($array) . ');', $model->serialize());
 }
开发者ID:benivaldo,项目名称:zf2-na-pratica,代码行数:7,代码来源:JsonModelTest.php

示例15: updateAction

 /**
  * 更新安全密码
  *
  * @author young
  * @name 更新安全密码
  * @version 2014.01.02 young
  * @return JsonModel
  */
 public function updateAction()
 {
     $oldPassword = trim($this->params()->fromPost('oldPassword', ''));
     $password = trim($this->params()->fromPost('password', ''));
     $repeatPassword = trim($this->params()->fromPost('repeatPassword', ''));
     $active = filter_var($this->params()->fromPost('active', ''), FILTER_VALIDATE_BOOLEAN);
     $criteria = array('project_id' => $this->_project_id, 'collection_id' => $this->_collection_id);
     $lockInfo = $this->_lock->findOne($criteria);
     if ($lockInfo != null) {
         if (empty($oldPassword)) {
             return $this->msg(true, '请输入原密码');
         }
         if (sha1($oldPassword) !== $lockInfo['password']) {
             return $this->msg(true, '身份验证未通过');
         }
     }
     if (empty($password) || empty($repeatPassword)) {
         return $this->msg(true, '请输入新密码或者确认密码');
     }
     if ($password !== $repeatPassword) {
         return $this->msg(true, '两次密码输入不一致');
     }
     $datas = array('password' => sha1($password), 'active' => $active);
     if ($active) {
         $rst = $this->_lock->update($criteria, array('$set' => $datas), array('upsert' => true));
         if ($rst['ok']) {
             return $this->msg(true, '设定集合访问密钥成功');
         } else {
             return $this->msg(false, Json::encode($rst));
         }
     } else {
         $this->_lock->remove($criteria);
         return $this->msg(true, '清除安全密钥成功');
     }
 }
开发者ID:im286er,项目名称:ent,代码行数:43,代码来源:LockController.php


注:本文中的Zend\Json\Json::encode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。