php中JSON的使用與轉(zhuǎn)換
Jun 06, 2016 pm 08:14 PM這篇文章主要介紹了php中JSON的使用與轉(zhuǎn)換,講解的十分細(xì)致全面,是篇非常不錯的文章,需要的朋友可以參考下
在之前我寫過php返回json數(shù)據(jù)簡單實例,剛剛上網(wǎng),突然發(fā)現(xiàn)一篇文章,也是介紹json的,還挺詳細(xì),值得參考。內(nèi)容如下
從5.2版本開始,PHP原生提供json_encode()和json_decode()函數(shù),前者用于編碼,后者用于解碼。
一、json_encode()
復(fù)制代碼 代碼如下:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
輸出
復(fù)制代碼 代碼如下:
{"a":1,"b":2,"c":3,"d":4,"e":5}
再看一個對象轉(zhuǎn)換的例子:
復(fù)制代碼 代碼如下:
$obj->body?????????? = 'another post';
$obj->id???????????? = 21;
$obj->approved?????? = true;
$obj->favorite_count = 1;
$obj->status???????? = NULL;
echo json_encode($obj);
?輸出
復(fù)制代碼 代碼如下:
{
"body":"another post",
"id":21,
"approved":true,
"favorite_count":1,
"status":null
}
?由于json只接受utf-8編碼的字符,所以json_encode()的參數(shù)必須是utf-8編碼,否則會得到空字符或者null。當(dāng)中文使用GB2312編碼,或者外文使用ISO-8859-1編碼的時候,這一點要特別注意。
二、索引數(shù)組和關(guān)聯(lián)數(shù)組
PHP支持兩種數(shù)組,一種是只保存"值"(value)的索引數(shù)組(indexed array),另一種是保存"名值對"(name/value)的關(guān)聯(lián)數(shù)組(associative array)。
由于javascript不支持關(guān)聯(lián)數(shù)組,所以json_encode()只將索引數(shù)組(indexed array)轉(zhuǎn)為數(shù)組格式,而將關(guān)聯(lián)數(shù)組(associative array)轉(zhuǎn)為對象格式。
比如,現(xiàn)在有一個索引數(shù)組
復(fù)制代碼 代碼如下:
$arr = Array('one', 'two', 'three');
echo json_encode($arr);
?輸出
復(fù)制代碼 代碼如下:
["one","two","three"]
?如果將它改為關(guān)聯(lián)數(shù)組:
復(fù)制代碼 代碼如下:
$arr = Array('1'=>'one', '2'=>'two', '3'=>'three');
echo json_encode($arr);
?輸出變?yōu)?/p>
復(fù)制代碼 代碼如下:
{"1":"one","2":"two","3":"three"}
?注意,數(shù)據(jù)格式從"[]"(數(shù)組)變成了"{}"(對象)。
如果你需要將"索引數(shù)組"強制轉(zhuǎn)化成"對象",可以這樣寫
復(fù)制代碼 代碼如下:
json_encode( (object)$arr );
?或者
復(fù)制代碼 代碼如下:
json_encode ( $arr, JSON_FORCE_OBJECT );
?三、類(class)的轉(zhuǎn)換
下面是一個PHP的類:
復(fù)制代碼 代碼如下:
class Foo {
const???? ERROR_CODE = '404';
public??? $public_ex = 'this is public';
private?? $private_ex = 'this is private!';
protected $protected_ex = 'this should be protected';
public function getErrorCode() {
return self::ERROR_CODE;
}
}
?現(xiàn)在,對這個類的實例進行json轉(zhuǎn)換:
復(fù)制代碼 代碼如下:
$foo = new Foo;
$foo_json = json_encode($foo);
echo $foo_json;
?輸出結(jié)果是
復(fù)制代碼 代碼如下:
{"public_ex":"this is public"}
?可以看到,除了公開變量(public),其他東西(常量、私有變量、方法等等)都遺失了。
四、json_decode()
該函數(shù)用于將json文本轉(zhuǎn)換為相應(yīng)的PHP數(shù)據(jù)結(jié)構(gòu)。下面是一個例子:
復(fù)制代碼 代碼如下:
$json = '{"foo": 12345}';
$obj = json_decode($json);
print $obj->{'foo'}; // 12345
?通常情況下,json_decode()總是返回一個PHP對象,而不是數(shù)組。比如:
復(fù)制代碼 代碼如下:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?結(jié)果就是生成一個PHP對象:
復(fù)制代碼 代碼如下:
object(stdClass)#1 (5) {
?
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
?
}
?如果想要強制生成PHP關(guān)聯(lián)數(shù)組,json_decode()需要加一個參數(shù)true:
復(fù)制代碼 代碼如下:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));
?結(jié)果就生成了一個關(guān)聯(lián)數(shù)組:
復(fù)制代碼 代碼如下:
array(5) {
? ["a"] => int(1)
? ["b"] => int(2)
? ["c"] => int(3)
? ["d"] => int(4)
? ["e"] => int(5)
}
五、json_decode()的常見錯誤
下面三種json寫法都是錯的,你能看出錯在哪里嗎?
復(fù)制代碼 代碼如下:
$bad_json = "{ 'bar': 'baz' }";
$bad_json = '{ bar: "baz" }';
$bad_json = '{ "bar": "baz", }';
?對這三個字符串執(zhí)行json_decode()都將返回null,并且報錯。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

To build a flexible PHP microservice, you need to use RabbitMQ to achieve asynchronous communication, 1. Decouple the service through message queues to avoid cascade failures; 2. Configure persistent queues, persistent messages, release confirmation and manual ACK to ensure reliability; 3. Use exponential backoff retry, TTL and dead letter queue security processing failures; 4. Use tools such as supervisord to protect consumer processes and enable heartbeat mechanisms to ensure service health; and ultimately realize the ability of the system to continuously operate in failures.

Use subprocess.run() to safely execute shell commands and capture output. It is recommended to pass parameters in lists to avoid injection risks; 2. When shell characteristics are required, you can set shell=True, but beware of command injection; 3. Use subprocess.Popen to realize real-time output processing; 4. Set check=True to throw exceptions when the command fails; 5. You can directly call chains to obtain output in a simple scenario; you should give priority to subprocess.run() in daily life to avoid using os.system() or deprecated modules. The above methods override the core usage of executing shell commands in Python.

Using the correct PHP basic image and configuring a secure, performance-optimized Docker environment is the key to achieving production ready. 1. Select php:8.3-fpm-alpine as the basic image to reduce the attack surface and improve performance; 2. Disable dangerous functions through custom php.ini, turn off error display, and enable Opcache and JIT to enhance security and performance; 3. Use Nginx as the reverse proxy to restrict access to sensitive files and correctly forward PHP requests to PHP-FPM; 4. Use multi-stage optimization images to remove development dependencies, and set up non-root users to run containers; 5. Optional Supervisord to manage multiple processes such as cron; 6. Verify that no sensitive information leakage before deployment
