search
HomeBackend DevelopmentPHP TutorialDetailed explanation of json format control in php

Detailed explanation of json format control in php

Dec 27, 2017 pm 05:58 PM
javascriptjsonphp

JSON is widely used in data transmission due to its high-performance transmission and analysis. This article mainly introduces relevant information on in-depth analysis of php json format control. I hope to be helpful.

Regarding the issue of json, novice friends have come to me one after another to ask, for example, why I output {"1":"item1","2":"item2","3":"item3 "} instead of ["item1","item2","item3"].

php array and js array

I use the above syntax of php 5.4 here.

There are associative arrays and index arrays in php, for example:


##

<?php
// 索引数组
$arr = [&#39;item1&#39;, &#39;item2&#39;, &#39;item3&#39;];
// 关联数组
$arr = [
 &#39;name&#39; => &#39;张三&#39;,
 &#39;age&#39; => &#39;22&#39;,
];


and js There is only one kind of array in there, and that is the index array. Maybe you will say that you can use K/V key-value pairs to simulate associative arrays.

K/V key-value pair looks like it, but it does not have any array characteristics, so it will not be explained in detail here.


The json formats obtained after json_encoding the above php array are ["item1", "item2", "item3"] and {"name":"\u5f20\u4e09","age ":"twenty two"}. The Chinese here has been converted to Unicode. If you insist on displaying Chinese, PHP 5.4 supports the JSON_UNESCAPED_UNICODE parameter. json_encode($arr, JSON_UNESCAPED_UNICODE) can get {"name":"Zhang San","age":"22" }, but it is highly not recommended to write like this.


What we get here are arrays under js and json strings in object format. So why are these two types generated? In other words, under what circumstances will object format be generated and under what circumstances will arrays be generated? What about the format.


php Array Output Format Control

I have listed the general situations, just look at the code.


<?php
$arr = [ // 不是 0 开始,会输出对象
 1 => &#39;item1&#39;,
 2 => &#39;item2&#39;,
 3 => &#39;item3&#39;,
];
echo "输出对象: ", json_encode($arr), "\n";
// 输出对象: {"1":"item1","2":"item2","3":"item3"}
$arr = [ // 连续索引,输出数组
 0 => &#39;item1&#39;,
 1 => &#39;item2&#39;,
 2 => &#39;item3&#39;,
];
echo "输出数组: ", json_encode($arr), "\n";
// 输出数组: ["item1","item2","item3"]
$arr = [ // 连续索引,输出数组 
 &#39;item1&#39;,
 &#39;item2&#39;,
 &#39;item3&#39;,
];
echo "输出数组: ", json_encode($arr), "\n";
// 输出数组: ["item1","item2","item3"]
$arr = [ // 索引不连续,输出对象
 0 => &#39;item1&#39;,
 1 => &#39;item2&#39;,
 2 => &#39;item3&#39;,
 5 => &#39;item5&#39;,
];
echo "输出对象: ", json_encode($arr), "\n";
// 输出对象: {"0":"item1","1":"item2","2":"item3","5":"item5"}
$arr = [ // 包含关联索引,一定输出对象
 0 => &#39;item1&#39;,
 1 => &#39;item2&#39;,
 2 => &#39;item3&#39;,
 &#39;other&#39; => &#39;其他字段&#39;
];
echo "输出对象: ", json_encode($arr), "\n";
// 输出对象: {"0":"item1","1":"item2","2":"item3","other":"\u5176\u4ed6\u5b57\u6bb5"}
// 关联数组 + 索引数组 实例
$arr = [ // 关联数组
 &#39;other&#39; => &#39;其他字段&#39;,
 &#39;count&#39; => 3, // 数组个数
 &#39;list&#39; => [ // 索引数组
  &#39;item1&#39;,
  &#39;item2&#39;,
  &#39;item3&#39;,
 ],
];
echo "对象+数组: ", json_encode($arr), "\n";
// 对象+数组: {"other":"\u5176\u4ed6\u5b57\u6bb5","count":3,"list":["item1","item2","item3"]}


In fact, the first type is a problem that many novice friends often encounter.

Because after the database is read out, they like to use the id as an index, and the id of the database does not start from 0. Take a look at this example.


$arr = $User->where($where)->find(); // 读取数据
$list = [];
foreach($arr as $key => $val) { // 遍历数组
 $list[$key] = [
  &#39;name&#39; => $val[&#39;name&#39;],
  &#39;age&#39; => $val[&#39;age&#39;],
 ];
}
$list[&#39;count&#39;] = count($arr); // 其他属性
echo json_encode($list); // 输出 json
// {"1":{"name":"zhangsan","age":22},"2":{"name":"lisi","age":25},"count":2}


The last one is a more common way of writing. Use custom fields and arrays together to modify the example just now.



$arr = $User->where($where)->find(); // 读取数据
$list = [];
foreach($arr as $key => $val) { // 遍历数组
 $list[&#39;list&#39;][] = [ // 修改这里
  &#39;name&#39; => $val[&#39;name&#39;],
  &#39;age&#39; => $val[&#39;age&#39;],
 ];
}
$list[&#39;count&#39;] = count($arr); // 其他属性
echo json_encode($list); // 输出 json
// {"list":[{"name":"zhangsan","age":22},{"name":"lisi","age":25}],"count":2}



##Related recommendations:

PHP solves the JSON Chinese display problem

php converts the index array into json

Introduction to usage examples of json_encode in php

The above is the detailed content of Detailed explanation of json format control in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)