本文整理汇总了PHP中to_json函数的典型用法代码示例。如果您正苦于以下问题:PHP to_json函数的具体用法?PHP to_json怎么用?PHP to_json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_json函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: to_json
function to_json(array $data)
{
$isArray = true;
$keys = array_keys($data);
$prevKey = -1;
// Необходимо понять — перед нами список или ассоциативный массив.
foreach ($keys as $key) {
if (!is_numeric($key) || $prevKey + 1 != $key) {
$isArray = false;
break;
} else {
$prevKey++;
}
}
unset($keys);
$items = array();
foreach ($data as $key => $value) {
$item = !$isArray ? "\"{$key}\":" : '';
if (is_array($value)) {
$item .= to_json($value);
} elseif (is_null($value)) {
$item .= 'null';
} elseif (is_bool($value)) {
$item .= $value ? 'true' : 'false';
} elseif (is_string($value)) {
$item .= '"' . preg_replace('%([\\x00-\\x1f\\x22\\x5c])%e', 'sprintf("\\\\u%04X", ord("$1"))', $value) . '"';
} elseif (is_numeric($value)) {
$item .= $value;
} else {
throw new Exception('Wrong argument.');
}
$items[] = $item;
}
return ($isArray ? '[' : '{') . implode(',', $items) . ($isArray ? ']' : '}');
}
示例2: check_required_get_params
/**
* Checks required GET parameters and dies if they are not valid or found
*
* @param $params
* The $_GET parameters in an array like: 'cid' => 'numeric', 'cid' => 'string'
* @return
* FALSE if params invalid or missing
*
*/
function check_required_get_params($params)
{
$errors = array();
foreach ($params as $key => $type) {
switch ($type) {
case 'numeric':
if (!isset($_GET[$key]) || !is_numeric($_GET[$key])) {
$errors[] = "Missing or invalid required param: {$key} ({$type})";
}
break;
case 'string':
if (!isset($_GET[$key])) {
$errors[] = "Missing or invalid required param: {$key} ({$type})";
}
break;
default:
if (!isset($_GET[$key])) {
$errors[] = "Missing or invalid required param: {$key} ({$type})";
}
}
}
if (isset($errors[0])) {
die(to_json(array('success' => FALSE, 'code' => 15, 'errors' => $errors)));
}
}
示例3: format_inline
function format_inline($inline, $num, $id, $preview_html = null)
{
if (!$inline->inline_images) {
return "";
}
$url = $inline->inline_images->first->preview_url();
if (!$preview_html) {
$preview_html = '<img src="' . $url . '">';
}
$id_text = "inline-{$id}-{$num}";
$block = '
<div class="inline-image" id="' . $id_text . '">
<div class="inline-thumb" style="display: inline;">
' . $preview_html . '
</div>
<div class="expanded-image" style="display: none;">
<div class="expanded-image-ui"></div>
<span class="main-inline-image"></span>
</div>
</div>
';
$inline_id = "inline-{$id}-{$num}";
$script = 'InlineImage.register("' . $inline_id . '", ' . to_json($inline) . ');';
return array($block, $script, $inline_id);
}
示例4: avatar_init
function avatar_init()
{
$posts = Comment::avatar_post_reg(true);
if (!$posts) {
return;
}
$ret = '';
foreach ($posts as $post) {
$ret .= "Post.register(" . to_json($post) . ")\n";
}
$ret .= 'Post.init_blacklisted';
return $ret;
}
示例5: autoContentType
protected function autoContentType($data)
{
if (gettype($data) == "string") {
$content_type = 'text/html';
$body = $data;
} else {
$content_type = 'application/json';
$body = to_json($data);
}
// only set content-type if it wans't set manually.
if ($this->app->response->headers->get('Content-type') == "text/html") {
$this->app->response->headers->set('Content-type', $content_type);
}
$this->app->response->setBody($body);
}
示例6: respond_to_list
function respond_to_list($inst_var)
{
// $inst_var = instance_variable_get("@#{inst_var_name}")
// global $$inst_var_name;
// $inst_var = &$$inst_var_name;
switch (Request::$format) {
case 'json':
if (method_exists($inst_var, 'to_json')) {
render('json', $inst_var->to_json());
} else {
render('json', to_json($inst_var));
}
break;
case 'xml':
break;
}
}
示例7: render
static function render($type, $value = null, $params = array())
{
if ($type === false) {
self::$params['nothing'] = true;
return;
}
if (is_int(strpos($type, '#'))) {
/**
* We're rendering a controller/action file.
* In this case, $value holds the params, and we only change
* the 'render' value and return. We can't call the
* render file within this or any function because of variables scope.
*
* This is expected to occur in a controller, therefore in the controller one must
* also return; after calling this function, so further code won't be executed.
*/
list($ctrl, $act) = explode('#', parse_url_token($type));
self::parse_parameters($value);
self::$render = VIEWPATH . "{$ctrl}/{$act}.php";
return;
}
# Running after-filters.
ActionController::run_after_filters();
self::parse_parameters($params);
if ($type == 'json') {
header('Content-Type: application/json; charset=utf-8');
if (is_array($value)) {
$value = to_json($value);
}
echo $value;
exit;
} elseif ($type == 'xml') {
header('Content-type: application/rss+xml; charset=UTF-8');
if (is_array($value) || is_object($value)) {
$root = isset($params['root']) ? $params['root'] : 'response';
$value = to_xml($value, $root);
}
echo $value;
exit;
} elseif ($type == 'inline') {
self::$params['render_type'] = 'inline';
self::$params['render_value'] = $value;
include SYSROOT . 'action_view/render_markup_default.php';
}
}
示例8: serialize
public static function serialize($protocolMessage)
{
if (!is_a($protocolMessage, 'ProtocolMessage')) {
throw new ProtocolMessageSerializationException('Provided object is not a ProtocolMessage.');
}
if (!$protocolMessage->validate()) {
throw new ProtocolMessageSerializationException('Provided object fails validation.');
}
/*$array = array();
foreach ($protocolMessage as $key => $value) {
$array[$key] = $value;
}*/
$serial = to_json($protocolMessage);
if ($serial === null) {
throw new ProtocolMessageSerializationException('Unable to serialize message (unknown encoding error): ' . json_last_error_msg());
}
return $serial;
}
示例9: remove_post_confirm
?>
</ul>
</div>
</div>
<script type="text/javascript">
function remove_post_confirm(post_id, pool_id) {
if (!$("del-mode") || !$("del-mode").checked) {
return true
}
Pool.remove_post(post_id, pool_id)
return false
}
Post.register_resp(<?php
echo to_json(Post::batch_api_data($posts));
?>
);
</script>
<?php
echo render_partial('post/hover');
?>
<div id="paginator">
<?php
paginator();
?>
<div style="display: none;" id="info">When delete mode is enabled, clicking on a thumbnail will remove the post from this pool.</div>
</div>
<?php
示例10: zopim_customize_widget
function zopim_customize_widget()
{
global $current_user;
$ul = $current_user->data->first_name;
$useremail = $current_user->data->user_email;
$greetings = json_to_array(get_option('zopimGreetings'));
$message = "";
if (count($_POST) > 0) {
update_option('zopimLang', $_POST["zopimLang"]);
update_option('zopimPosition', $_POST["zopimPosition"]);
update_option("zopimBubbleEnable", $_POST["zopimBubbleEnable"]);
update_option('zopimColor', $_POST["zopimColor"]);
update_option('zopimTheme', $_POST["zopimTheme"]);
update_option('zopimBubbleTitle', stripslashes($_POST["zopimBubbleTitle"]));
update_option('zopimBubbleText', stripslashes($_POST["zopimBubbleText"]));
update_checkbox("zopimGetVisitorInfo");
update_checkbox("zopimHideOnOffline");
update_checkbox("zopimUseGreetings");
update_checkbox("zopimUseBubble");
if (isset($_POST['zopimUseGreetings']) && $_POST['zopimUseGreetings'] != "") {
$greetings->online->window = stripslashes($_POST["zopimOnlineLong"]);
$greetings->online->bar = stripslashes($_POST["zopimOnlineShort"]);
$greetings->away->window = stripslashes($_POST["zopimAwayLong"]);
$greetings->away->bar = stripslashes($_POST["zopimAwayShort"]);
$greetings->offline->window = stripslashes($_POST["zopimOfflineLong"]);
$greetings->offline->bar = stripslashes($_POST["zopimOfflineShort"]);
update_option('zopimGreetings', to_json($greetings));
}
$message = "<b>Changes saved!</b><br>";
}
zopimme();
$accountDetails = getAccountDetails(get_option('zopimSalt'));
if (get_option('zopimCode') == "zopim") {
$message = '<div class="metabox-holder">
<div class="postbox">
<h3 class="hndle"><span>Customizing in Demo Mode</span></h3>
<div style="padding:10px;line-height:17px;">
Currently customizing in demo mode. Messages in this widget will go to Zopim staff. The chat widget will not appear on your site until you <a href="admin.php?page=zopim_account_config">activate / link up an account</a>. <br>
</div>
</div>
</div>';
$accountDetails->widget_customization_enabled = 1;
$accountDetails->color_customization_enabled = 1;
} else {
if (isset($accountDetails->error)) {
$message = '<div class="metabox-holder">
<div class="postbox">
<h3 class="hndle"><span>Account no longer linked!</span></h3>
<div style="padding:10px;line-height:17px;">
We could not connect to your Zopim account. As a result, this customization page is running in demo mode.<br> Please <a href="admin.php?page=zopim_account_config">check your password in account setup</a> and try again.
</div>
</div>
</div>';
} else {
$message .= "Click 'Save Changes' when you're done. Happy customizing!";
}
}
// unset($accountDetails->widget_customization_enabled);
// unset($accountDetails->color_customization_enabled);
?>
<script type="text/javascript">
function updateWidget() {
var lang = document.getElementById('zopimLang').options[ document.getElementById('zopimLang').options.selectedIndex ].value;
$zopim.livechat.setLanguage(lang);
if (document.getElementById("zopimGetVisitorInfo").checked) {
$zopim.livechat.setName('<?php
echo $ul;
?>
');
$zopim.livechat.setEmail('<?php
echo $useremail;
?>
');
}
else {
$zopim.livechat.setName('Visitor');
$zopim.livechat.setEmail('');
}
document.getElementById("zopimHideOnOffline").checked? $zopim.livechat.button.setHideWhenOffline(true): $zopim.livechat.button.setHideWhenOffline(false);
$zopim.livechat.window.setColor(document.getElementById("zopimColor").value);
$zopim.livechat.window.setTheme(document.getElementById("zopimTheme").value);
if (document.getElementById("zopimUseBubble").checked) {
$zopim.livechat.bubble.setTitle(document.getElementById("zopimBubbleTitle").value);
$zopim.livechat.bubble.setText(document.getElementById("zopimBubbleText").value);
}
else {
$zopim.livechat.bubble.setTitle('Questions?');
$zopim.livechat.bubble.setText('Click here to chat with us!');
}
$zopim.livechat.setGreetings({
'online': [document.getElementById("zopimOnlineShort").value, document.getElementById("zopimOnlineLong").value],
'offline': [document.getElementById("zopimOfflineShort").value, document.getElementById("zopimOfflineLong").value],
'away': [document.getElementById("zopimAwayShort").value, document.getElementById("zopimAwayLong").value]
//.........这里部分代码省略.........
示例11: session_start
<?php
/**
* @file
* Get tweet details based on a twitter id
*/
session_start();
require_once $_SERVER['DOCUMENT_ROOT'] . '/config/main.conf.php';
require $_SERVER['DOCUMENT_ROOT'] . '/lib/helpers.php';
require $_SERVER['DOCUMENT_ROOT'] . '/lib/twitoauth/twitteroauth.php';
/* If access tokens are not available redirect to connect page. */
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: /twitoauth/clearsessions.php');
exit;
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$connection->decode_json = TRUE;
$result = $connection->post("friendships/create/{$_GET['screen_name']}");
$success = isset($result->id) ? TRUE : FALSE;
$message = isset($result->errors) ? $result->errors : NULL;
$return_array = array('success' => $success, 'message' => $message);
$json_string = to_json($return_array);
error_log("favorites JSON String: " . $json_string);
print $json_string;
示例12: while
INNER JOIN status_channel ON status.id = status_channel.status_id
WHERE (status_channel.channel_id = ? ' . $chanzero . ') AND id < ?
ORDER BY status_channel.status_id DESC LIMIT ?');
$stmt->bind_param('idi', $_GET['cid'], $_GET['maxid'], $limit);
} else {
$stmt = $mysqli->prepare('SELECT id, screen_name, profile_image_url, created_at, source, text
FROM status
INNER JOIN status_channel ON status.id = status_channel.status_id
WHERE status_channel.channel_id = ? ' . $chanzero . '
ORDER BY status_channel.status_id DESC LIMIT ?');
$stmt->bind_param('ii', $_GET['cid'], $limit);
}
$stmt->execute();
$stmt->bind_result($id, $screen_name, $profile_image_url, $created_at, $source, $text);
$next_page_maxid = NULL;
while ($stmt->fetch()) {
$created_at_timestamp = strtotime($created_at);
$tweets[] = array('id' => $id, 'screen_name' => $screen_name, 'profile_image_url' => $profile_image_url, 'created_at' => nice_time($created_at_timestamp), 'created_at_long' => date('m-d-y h:i A', $created_at_timestamp), 'source' => $source, 'text' => $text);
$next_page_maxid = $id;
}
$stmt->close();
$return_array = array('tweets' => $tweets, 'next_page_maxid' => $next_page_maxid);
print to_json($return_array);
if ($do_cache) {
$contents = ob_get_contents();
ob_end_clean();
$handle = fopen($cachefile, 'w');
fwrite($handle, $contents);
fclose($handle);
include $cachefile;
}
示例13: to_json
function to_json($params = array())
{
return to_json($this->api_attributes(), $params);
}
示例14: paginator
<div id="paginator">
<?php
paginator();
?>
</div>
<?php
do_content_for("post_cookie_javascripts");
?>
<script type="text/javascript">
var thumb = $("hover-thumb");
<?php
foreach ($samples as $k => $post) {
?>
Post.register(<?php
echo to_json($post);
?>
);
var hover_row = $("p<?php
echo $pools->{$k}->id;
?>
");
var container = hover_row.up("TABLE");
Post.init_hover_thumb(hover_row, <?php
echo $post->id;
?>
, thumb, container);
<?php
}
?>
Post.init_blacklisted({replace: true});
示例15: get
<?php
require_once "getquery.php";
$species = get("species");
$query = "\nSELECT\n a.id as \"id\",\n a.name as \"name\",\n a.description as \"description\"\nFROM\n ability as a";
if ($species) {
$query .= "\n ,\n species as s\nWHERE\n s.id={$species}\n AND a.id <>0\n AND (\n s.ability1=a.id OR\n s.ability2=a.id OR\n s.ability3=a.id\n )\n;";
}
$result = run_query($query);
echo to_json($result);