本文整理汇总了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)));
}
示例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;
}
示例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);
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例8: arrayToJsonString
public static function arrayToJsonString($aDane)
{
ob_start();
echo \Zend\Json\Json::encode($aDane);
$sOut = ob_get_clean();
return $sOut;
}
示例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;
}
示例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);
}
示例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> ';
}
$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;
}
示例12: convertToDatabaseValue
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if (null === $value) {
return null;
}
return Json::encode($value);
}
示例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;
}
示例14: testCanSerializeWithJsonpCallback
public function testCanSerializeWithJsonpCallback()
{
$array = array('foo' => 'bar');
$model = new JsonModel($array);
$model->setJsonpCallback('callback');
$this->assertEquals('callback(' . Json::encode($array) . ');', $model->serialize());
}
示例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, '清除安全密钥成功');
}
}