本文整理汇总了PHP中Json类的典型用法代码示例。如果您正苦于以下问题:PHP Json类的具体用法?PHP Json怎么用?PHP Json使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Json类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: parseMustReturnArray
/**
* @test
*/
public function parseMustReturnArray()
{
$expected = ['some' => 1, 'valid' => false, 'payloads' => [1, "10", 1.1, null, true]];
$json = new Json();
$parsed = $json->parse(json_encode($expected));
$this->assertEquals($expected, $parsed);
}
开发者ID:Leko,项目名称:permitter,代码行数:10,代码来源:JsonTest.php
示例2: gerateBilling
public function gerateBilling()
{
$order = null;
$customers = $this->getUserID();
$structJsonArray = array();
foreach ($customers as $customer) {
$structJson = new Json();
$structJson->setCustomerId($customer['zoho_books_contact_id']);
$structJson->setDate(date('d-m-Y'));
$invoices_per_costumer = $this->getUserInvoice($customer['zoho_books_contact_id']);
//var_dump($invoices_per_costumer);
foreach ($invoices_per_costumer as $invoice_each) {
$item = new Item();
$order++;
$item->setItemId("460000000027017");
$item->setProjectId("");
$item->setExpenseId("");
$item->setName("Print Services");
$item->setDescription($invoice_each['description']);
$item->setItemOrder($order);
$item->setRate($invoice_each['rate']);
$item->setUnit("Nos");
$item->setQuantity(1.0);
$item->setDiscount(0.0);
$item->setTaxId("460000000027005");
$structJson->setLineItems($item);
$item = null;
}
$structJson->setNotes("Thanks for your business.");
$order = null;
$structJsonArray[] = $structJson;
$structJson = null;
}
return $structJsonArray;
}
开发者ID:denisolvr,项目名称:Billing-Code-Test,代码行数:35,代码来源:Bill.php
示例3: setJsonResponse
public function setJsonResponse(Json $json)
{
if ($this->error) {
$json->setError($this->error, $this->statusCode);
}
$this->response = $json->__toString();
}
开发者ID:asanoturna,项目名称:finance-2,代码行数:7,代码来源:HttpResponse.php
示例4: 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));
}
开发者ID:sanplit,项目名称:huishou,代码行数:11,代码来源:utiljson.php
示例5: test_parse_returnsSelf_ifOutputIsValid
/**
* parse() should return true if $output is valid json
*/
public function test_parse_returnsSelf_ifOutputIsValid()
{
$output = '{"foo":"bar"}';
$response = new Json();
$this->assertTrue($response->parse($output));
$this->assertEquals(['foo' => 'bar'], $response->getData());
return;
}
开发者ID:jstewmc,项目名称:api,代码行数:11,代码来源:JsonTest.php
示例6: serialize
/**
* Serialize array to JSON string.
*
* @param array $args
* @return string
* @throws GraphCommons\Util\JsonException
*/
public function serialize(...$args) : string
{
$json = new Json($this->unserialize());
if ($json->hasError()) {
$jsonError = $json->getError();
throw new JsonException(sprintf('JSON error: code(%d) message(%s)', $jsonError['code'], $jsonError['message']), $jsonError['code']);
}
return (string) $json->encode($args);
}
开发者ID:graphcommons,项目名称:graphcommons-php7,代码行数:16,代码来源:SerialTrait.php
示例7: testWrite
/**
* Tests Json::write
*/
public function testWrite()
{
$json = new Json();
$json->setup(['target' => 'php://output']);
ob_flush();
ob_start();
$json->write(['foo' => 'bar']);
$output = ob_get_clean();
$this->assertEquals('{"foo":"bar"}', $output);
}
开发者ID:imjerrybao,项目名称:phpbu,代码行数:13,代码来源:JsonTest.php
示例8: output
/**
* 页面内容输出
* @param boolean $fetch 是否提取输出结果
* @return string JSON结果
*/
function output($fetch = false)
{
ob_start();
$json = new Json();
echo $json->encode($this->value);
$content = ob_get_contents();
if ($fetch) {
ob_end_clean();
} else {
ob_end_flush();
}
return $content;
}
开发者ID:a4m,项目名称:go1den-express,代码行数:18,代码来源:PageJson.class.php
示例9: extendPostRequest
public function extendPostRequest($aMerchantNo)
{
try {
$this->iLogWriter = new LogWriter();
$this->iLogWriter->logNewLine("TrustPayClient V3.0.0 交易开始==========================");
MerchantConfig::getLogWriterObject($this->iLogWriter);
//0、检查传入参数是否合法
if ($aMerchantNo <= 0 || $aMerchantNo > MerchantConfig::getMerchantNum()) {
throw new TrxException(TrxException::TRX_EXC_CODE_1008, TrxException::TRX_EXC_MSG_1008, '配置文件中商户数为' . MerchantConfig::getMerchantNum() . ", 但是请求指定的商户配置编号为{$aMerchantNo} !");
}
//1、检查交易请求是否合法
$this->iLogWriter->logNewLine('检查交易请求是否合法:');
$this->checkRequest();
$this->iLogWriter->log('正确');
//2、取得交易报文
$tRequestMessage = $this->getRequestMessage();
//3、组成完整交易报文
$this->iLogWriter->log("完整交易报文:");
$tRequestMessage = $this->composeRequestMessage($aMerchantNo, $tRequestMessage);
$this->iLogWriter->log($tRequestMessage);
//4、对交易报文进行签名
$tRequestMessage = MerchantConfig::signMessage($aMerchantNo, $tRequestMessage);
//5、发送交易报文至网上支付平台
$tResponseMessage = $this->sendMessage($tRequestMessage);
//6、验证网上支付平台响应报文的签名
$this->iLogWriter->logNewLine('验证网上支付平台响应报文的签名:');
MerchantConfig::verifySign($tResponseMessage);
$this->iLogWriter->log('正确');
//7、生成交易响应对象
$this->iLogWriter->logNewLine('生成交易响应对象:');
$this->iLogWriter->logNewLine('交易结果:[' . $tResponseMessage->getReturnCode() . ']');
$this->iLogWriter->logNewLine('错误信息:[' . $tResponseMessage->getErrorMessage() . ']');
} catch (TrxException $e) {
$tResponseMessage = new Json();
$tResponseMessage->initWithCodeMsg($e->getCode(), $e->getMessage() . " - " . $e->getDetailMessage());
if ($this->iLogWriter != null) {
$this->iLogWriter->logNewLine('错误代码:[' + $tResponseMessage->getReturnCode() . '] 错误信息:[' . $tResponseMessage->getErrorMessage() . ']');
}
} catch (Exception $e) {
$tResponseMessage = new Json();
$tResponseMessage->initWithCodeMsg(TrxException::TRX_EXC_CODE_1999, TrxException::TRX_EXC_MSG_1999 . ' - ' . $e->getMessage());
if ($this->iLogWriter != null) {
$this->iLogWriter->logNewLine('错误代码:[' . $tResponseMessage->getReturnCode() . '] 错误信息:[' . $tResponseMessage->getErrorMessage() . ']');
}
}
if ($this->iLogWriter != null) {
$this->iLogWriter->logNewLine("交易结束==================================================\n\n\n\n");
$this->iLogWriter->closeWriter(MerchantConfig::getTrxLogFile());
}
return $tResponseMessage;
}
开发者ID:pqshawn,项目名称:sparrowPHP,代码行数:51,代码来源:TrxRequest.php
示例10: 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));
}
开发者ID:svetel,项目名称:FBApp,代码行数:31,代码来源:manual.php
示例11: 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);
}
开发者ID:martinlindhe,项目名称:core_dev,代码行数:35,代码来源:YuiAutocomplete.php
示例12: 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' => '']);
}
开发者ID:adem-team,项目名称:advanced,代码行数:30,代码来源:BarangaliasController.php
示例13: Set
public static function Set($Filename, $Data, $Options = JSON_PRETTY_PRINT)
{
$Path = "config/{$Filename}.json";
$Return = Json::Encode($Path, $Data, $Options);
self::LoadFile($Filename);
return $Return;
}
开发者ID:kumar003vinod,项目名称:WhatsBot,代码行数:7,代码来源:Config.php
示例14: 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]);
}
开发者ID:pavel78779,项目名称:my_cms,代码行数:7,代码来源:HelpersController.php
示例15: testGetErrorMessage
/**
* Tests getErrorMessage.
*/
public function testGetErrorMessage()
{
$errors = array(JSON_ERROR_NONE => 'No errors', JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', 999999999 => 'Unknown error');
foreach ($errors as $no => $message) {
$this->assertSame($message, Json::getErrorMessage($no));
}
}
开发者ID:raphhh,项目名称:trex,代码行数:10,代码来源:JsonTest.php
示例16: __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: /');
}
开发者ID:joksnet,项目名称:php-old,代码行数:25,代码来源:Login.php
示例17: getRequestMessage
protected function getRequestMessage()
{
Json::arrayRecursive($this->request, "urlencode", false);
$tMessage = json_encode($this->request);
$tMessage = urldecode($tMessage);
return $tMessage;
}
开发者ID:pqshawn,项目名称:sparrowPHP,代码行数:7,代码来源:QuickIdentityVerifyRequest.php
示例18: 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));
}
开发者ID:howareyoucolin,项目名称:demo,代码行数:30,代码来源:reward.php
示例19: 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';
}
}
}
开发者ID:sayi21cn,项目名称:kyphp2.0,代码行数:33,代码来源:Json.php
示例20: __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 [email protected]')->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';
}
开发者ID:osmcz,项目名称:website,代码行数:34,代码来源:CommunityFormPlugin.php
注:本文中的Json类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论