本文整理汇总了PHP中Json::encode方法的典型用法代码示例。如果您正苦于以下问题:PHP Json::encode方法的具体用法?PHP Json::encode怎么用?PHP Json::encode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Json
的用法示例。
在下文中一共展示了Json::encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: get_data_for_main_page
public function get_data_for_main_page()
{
$db = new Db();
$components = $db->getAll("SELECT `title`,`name` FROM ##extensions WHERE `type`='component' AND `enabled`=1");
$modules = $db->getAll('SELECT `name`,`id` FROM ##modules WHERE `published`=1');
echo Json::encode([$components, $modules]);
}
示例2: actionProduct
/**
* Lists all Barangalias models.
* @return mixed
*/
public function actionProduct()
{
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$id = $parents[0];
$model = Barang::find()->asArray()->where(['PARENT' => $id])->andwhere('STATUS <> 3')->all();
// print_r($model);
// die();
//$out = self::getSubCatList($cat_id);
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
foreach ($model as $key => $value) {
$out[] = ['id' => $value['KD_BARANG'], 'name' => $value['NM_BARANG']];
}
echo json_encode(['output' => $out, 'selected' => '']);
return;
}
}
echo Json::encode(['output' => '', 'selected' => '']);
}
示例3: get
public function get()
{
$fields = explode(',', Request::get('fields', true, Validator::STRICT_STRING_COMMAS));
$filter = Request::get('filter', false, null);
if ($filter !== null) {
$filter = Json::decode($filter);
if (!$filter) {
throw new ValidatorException('Некорректный параметр filter');
}
foreach ($filter as $key => $value) {
Validator::strictString($key, 'Некорректный ключ для фильтра');
if (!in_array($key, $this->fields)) {
throw new ValidatorException('Поля для фильтра с именем "' . $key . '" не существует');
}
}
} else {
$filter = [];
}
foreach ($fields as $field) {
if (!in_array($field, $this->fields)) {
throw new ValidatorException('Поля с именем "' . $field . '" не существует в таблице базы данных');
}
if (isset($this->fieldOptions[$field])) {
if (strripos($this->fieldOptions[$field][0], 'r') === false) {
throw new ValidatorException('Поле "' . $field . '" недоступно для чтения');
}
}
}
echo Json::encode($this->_get($fields, $filter));
}
示例4: render
function render()
{
if (!$this->name) {
throw new \Exception('must set a name');
}
if (!$this->xhr_url) {
throw new \Exception('must set xhr url');
}
if (!$this->js_format_result || !$this->result_fields) {
throw new \Exception('need js code');
}
$header = XhtmlHeader::getInstance();
$header->includeCss('core_dev/js/ext/yui/2.9.0/build/fonts/fonts-min.css');
$header->includeCss('core_dev/js/ext/yui/2.9.0/build/autocomplete/assets/skins/sam/autocomplete.css');
$header->includeCss('core_dev/js/ext/yui/2.9.0/build/button/assets/skins/sam/button.css');
$header->includeJs('core_dev/js/ext/yui/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js');
$header->includeJs('core_dev/js/ext/yui/2.9.0/build/get/get-min.js');
$header->includeJs('core_dev/js/ext/yui/2.9.0/build/animation/animation-min.js');
$header->includeJs('core_dev/js/ext/yui/2.9.0/build/datasource/datasource-min.js');
$header->includeJs('core_dev/js/ext/yui/2.9.0/build/autocomplete/autocomplete-min.js');
$header->includeJs('core_dev/js/ext/yui/2.9.0/build/element/element-min.js');
$header->includeJs('core_dev/js/ext/yui/2.9.0/build/button/button-min.js');
$div_holder = 'yui_ac' . mt_rand();
$container_holder = 'ac_contain_' . mt_rand();
$button_id = 'ac_toggle_' . mt_rand();
$input_id = 'ac_input_' . mt_rand();
$header->embedJs('function highlight(s,h)' . '{' . 'var regex = new RegExp("("+h+")","ig");' . 'return s.replace(regex, "<span class=\\"highlighted\\">$1</span>");' . '}');
$header->embedCss('label {' . 'color:#E76300;' . 'font-weight:bold;' . '}' . '#' . $div_holder . ' {' . 'width:20em;' . '}' . '.yui-ac .result {position:relative;height:20px;}' . '.yui-ac .name {position:absolute;bottom:0;}' . '.highlighted {color:#CA485E;font-weight:bold; }' . '.yui-ac .yui-button {vertical-align:middle;}' . '.yui-ac .yui-button button {background: url(http://developer.yahoo.com/yui/examples/autocomplete/assets/img/ac-arrow-rt.png) center center no-repeat}' . '.yui-ac .open .yui-button button {background: url(http://developer.yahoo.com/yui/examples/autocomplete/assets/img/ac-arrow-dn.png) center center no-repeat}' . '.yui-skin-sam .yui-ac-input {position:static; vertical-align:middle;}' . '.yui-skin-sam .yui-ac-content {' . 'max-height:250px;overflow:auto;overflow-x:hidden;' . '}');
$res = 'YAHOO.example.CustomFormatting = (function(){' . 'var oDS = new YAHOO.util.ScriptNodeDataSource("' . $this->xhr_url . '");' . 'oDS.responseSchema = {' . 'resultsList:"records",' . 'fields:' . Json::encode($this->result_fields, false) . '};' . 'var oAC = new YAHOO.widget.AutoComplete("' . $input_id . '","' . $container_holder . '", oDS);' . 'oAC.minQueryLength = 0;' . 'oAC.queryDelay = ' . $this->query_delay . ';' . 'oAC.animSpeed = 0.01;' . 'oAC.maxResultsDisplayed = 100;' . 'oAC.forceSelection = true;' . 'oAC.generateRequest = function(sQuery) {' . 'return sQuery + "&format=json";' . '};' . 'oAC.resultTypeList = false;' . 'oAC.formatResult = function(oResultData, sQuery, sResultMatch) {' . $this->js_format_result . '};' . 'oAC.itemSelectEvent.subscribe(function(sType, aArgs) {' . 'var oData = aArgs[2];' . 'var input = document.createElement("input");' . 'input.setAttribute("type", "hidden");' . 'input.setAttribute("name", "' . $this->name . '");' . 'input.setAttribute("value", oData.id);' . 'document.getElementById("' . $div_holder . '").appendChild(input);' . '});' . 'var validateForm = function() {' . 'return true;' . '};' . 'return {' . 'oDS: oDS,' . 'oAC: oAC,' . 'validateForm: validateForm' . '}' . '})();';
$in = new XhtmlComponentInput();
$in->name = $input_id;
$in->width = 200;
// XXXX HACK, should not set width at all.. but we do it now so button dont end up on the next line
return '<div id="' . $div_holder . '">' . $in->render() . '<div id="' . $container_holder . '"></div>' . '</div>' . js_embed($res);
}
示例5: __construct
public function __construct()
{
global $config;
$username = strip_tags(addslashes(trim($_POST['username'])));
$password = md5(trim($_POST['password']));
$viewonly = $_POST['view'] == 1;
$sql = "SELECT user_id, hours\r\n FROM users\r\n WHERE username = '{$username}'\r\n AND password = '{$password}'";
if ($data = Db::query($sql)) {
$user_id = $data['user_id'];
$hours = $data['hours'];
if ($config['expires']) {
$expires = $config['expires'];
} else {
$expires = intval($hours) * 3600;
}
# if ( headers_sent($file, $line) )
# die( "Headers Sent on $file:$line" );
$modules = $this->getModules($user_id);
$data = array('username' => $username, 'viewOnly' => $viewonly, 'hours' => $hours, 'modules' => $modules);
Cookies::set('sid', md5($user_id), $expires);
Cookies::set('uid', $user_id, $expires);
Cookies::set('data', Json::encode($data), $expires);
}
header('Location: /');
}
示例6: shipping
public function shipping()
{
$json = array();
$this->load->library('user');
if ($this->user->isLogged()) {
$this->language->load('checkout/checkout');
$this->tax->setZone($shipping_address['country_id'], $shipping_address['zone_id']);
if (!isset($this->session->data['shipping_methods'])) {
$quote_data = array();
$this->load->model('setting/extension');
$results = $this->model_setting_extension->getExtensions('shipping');
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('shipping/' . $result['code']);
$quote = $this->{'model_shipping_' . $result['code']}->getQuote($shipping_address);
if ($quote) {
$quote_data[$result['code']] = array('title' => $quote['title'], 'quote' => $quote['quote'], 'sort_order' => $quote['sort_order'], 'error' => $quote['error']);
}
}
}
$sort_order = array();
foreach ($quote_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $quote_data);
$this->session->data['shipping_methods'] = $quote_data;
}
}
$this->load->library('json');
$this->response->setOutput(Json::encode($json));
}
示例7: __construct
public function __construct()
{
parent::__construct();
$this->tags = array();
$tags = PagesModel::getPageById(27)->getMeta('tag_options');
foreach (explode("\n", $tags) as $t) {
$t = trim($t);
$this->tags[$t] = $t;
}
$this->projects = PagesModel::getPagesByMeta("project_tag")->getPairs('');
$this->addText('username', 'OSM.org username')->setDisabled();
$this->addText('fullname', 'Celé jméno')->setOption('description', 'Ať se poznáme!')->addRule(Form::FILLED, '%label není vyplněn.')->addRule(Form::MIN_LENGTH, '%label musí mít alespoň 5 znaků.', 5);
$this->addText('email', 'Talk-cz')->setOption('description', 'Email použivaný pro spočítání příspěvků v talk-cz (neveřejný)')->addRule(Form::FILLED, '%label není vyplněn.')->addRule(Form::EMAIL, '%label není validní.');
$this->addText('contact', 'Veřejný e-mail')->setOption('description', '(nepovinné)')->addCondition(Form::FILLED)->addRule(Form::EMAIL, '%label není validní.');
$this->addText('twitter', 'Twitter')->setOption('description', '(nepovinné) Uživatelské jméno bez zavináče');
$this->addText('github', 'Github')->setOption('description', '(nepovinné) Uživatelské jméno');
$this->addText('places', 'Výskyt')->setOption('description', '(nepovinné) Kde se vyskystuju - typicky jaká města.');
$this['places']->getControlPrototype()->placeholder = 'oddělené čárkou';
$this['places']->getControlPrototype()->style = 'width: 40%';
$this->addText('tags', 'Oblasti zájmu')->setOption('description', '(nepovinné)');
$this['tags']->getControlPrototype()->placeholder = 'oddělené čárkou';
$this['tags']->getControlPrototype()->style = 'width: 60%';
$this['tags']->getControlPrototype()->{'data-options'} = Json::encode(array_values($this->tags));
$this->addMultiSelect('projects', 'Projekty', $this->projects)->setOption('description', '(nepovinné) Projektovou stránku možno přidat v administraci. Případně napiš na dev@openstreetmap.cz')->getControlPrototype()->style = 'height:150px;width:40%';
$this->addCheckbox('public', 'Zveřejnit údaje na openstreetmap.cz');
$this->addSubmit('submit', 'Uložit údaje');
$this->onSuccess[] = callback($this, 'submitted');
$renderer = $this->getRenderer();
$renderer->wrappers['controls']['container'] = 'table class="table form-inline"';
$renderer->wrappers['error']['container'] = 'ul class="bg-danger"';
$renderer->wrappers['control']['.text'] = 'form-control';
$renderer->wrappers['control']['.email'] = 'form-control';
$renderer->wrappers['control']['.submit'] = 'btn btn-primary';
}
示例8: encode
/**
* Encode the content to its JSON representation.
*
* @param string $content
*
* @return string
*/
protected function encode($content)
{
if ($this->hasValidCallback()) {
return sprintf('%s(%s);', $this->getCallback(), json_encode($content));
}
return parent::encode($content);
}
示例9: encode
public static function encode($data)
{
if (function_exists('json_encode')) {
return json_encode($data);
} else {
switch (gettype($data)) {
case 'boolean':
return $data ? 'true' : 'false';
case 'integer':
case 'double':
return $data;
case 'resource':
case 'string':
return '"' . str_replace(array("\r", "\n", "<", ">", "&"), array('\\r', '\\n', '\\x3c', '\\x3e', '\\x26'), addslashes($data)) . '"';
case 'array':
if (empty($data) || array_keys($data) === range(0, sizeof($data) - 1)) {
$output = array();
foreach ($data as $value) {
$output[] = Json::encode($value);
}
return '[ ' . implode(', ', $output) . ' ]';
}
case 'object':
$output = array();
foreach ($data as $key => $value) {
$output[] = Json::encode(strval($key)) . ': ' . Json::encode($value);
}
return '{ ' . implode(', ', $output) . ' }';
default:
return 'null';
}
}
}
示例10: calculate
public function calculate()
{
$this->language->load('total/reward');
$json = array();
if (isset($this->request->post['reward'])) {
if (!$this->request->post['reward']) {
$json['error'] = $this->language->get('error_empty');
}
$points = $this->customer->getRewardPoints();
if ($this->request->post['reward'] > $points) {
$json['error'] = sprintf($this->language->get('error_points'), $this->request->post['reward']);
}
$points_total = 0;
foreach ($this->cart->getProducts() as $product) {
if ($product['points']) {
$points_total += $product['points'];
}
}
if ($this->request->post['reward'] > $points_total) {
$json['error'] = sprintf($this->language->get('error_maximum'), $points_total);
}
if (!isset($json['error'])) {
$this->session->data['reward'] = $this->request->post['reward'];
$this->session->data['success'] = $this->language->get('text_success');
$json['redirect'] = $this->url->link('checkout/cart', '', 'SSL');
}
}
$this->load->library('json');
$this->response->setOutput(Json::encode($json));
}
示例11: doDefault
/**
* 显示登录页(默认Action)
*/
function doDefault()
{
$data = array('a', 'b' => 'roast');
$json = new Json();
$str_encoded = $json->encode($data);
var_dump($str_encoded);
var_dump($json->decode($str_encoded));
}
示例12: __toString
public function __toString()
{
$response = array('status' => $this->status, 'message' => $this->message, 'data' => $this->data);
switch ($this->outputType) {
case "json":
return Json::encode($response);
}
}
示例13: unsubscribe
/**
*
* @param EmailAddressesEntity $emails
*/
public function unsubscribe(EmailAddressesEntity $emails)
{
$request = Request::post("{$this->getCompanyId()}/unsubscribers/");
$data = $emails->toArray();
$json = Json::encode($data['emails']);
$request->setContent($json);
$this->getConnector()->sendRequest($request);
}
示例14: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
$form_state->cleanValues();
// This won't have a proper JSON header, but Drupal doesn't check for that
// anyway so this is fine until it's replaced with a JsonResponse.
print Json::encode($form_state->getValues());
exit;
}
示例15: registerAssets
/**
* Registers the needed assets
*/
public function registerAssets()
{
$view = $this->getView();
$id = $this->options['id'];
iziModalAsset::register($view);
$clientOptions = Json::encode([$this->clientOptions ?: new JsExpression('{}')]);
$js = "\$('#{$id}').iziModal({$clientOptions});";
$view->registerJs($js);
}