Thinking of json_encode/serialize caused by the storage array of a field in a database

Source: Internet
Author: User
Tags php language mysql in php script scalar serialization

Fuse Scene:

    • Original: MySQL in the result table img Field original storage string, content for a picture link;
    • Now: This field needs to store more than one picture link, 1-3 elements of the array of stroke;

There are two general recommendations that Google receives: Https://stackoverflow.com/questions/3413291/how-to-store-an-array-into-mysql

    • Recommendation one: Build multiple tables based on specific scenarios, forming associations through primary key foreign keys.

Pros: Support for queries against a field in an array; Cons: Need to combine specific scenarios

    • Recommendation two: Serializing arrays, PHP provides built-in methods to support serialization and deserialization (serialize/unserialize) (after development, it is found that there is still another serialization mode Json_encode/json_decode )

Advantages: easy to implement; Cons: Arrays are considered as a whole and do not support manipulation of individual elements;

There are no actions such as queries for individual picture links, select recommendation Two.

issue: interface postman img parameter one column value write [xxx,xxx], serialized after Inbound, get deserialized expected return array of arguments [xxx,xxx], Actually returns a string of type "[Xxx,xxx]"

Troubleshooting Process : GetType view data type in PHP, enter argument is string type, Json_decode is array type

reason:postman img Parameter column value writes [XXX,XXX], which is actually a string type, an array of JSON type.

Follow-up : The understanding of JSON type has been too superficial, take this opportunity to learn, the relevant information let me enlightened, summed up to share the following.

1. JSON can be understood as a string that conforms to a certain writing format, and the substance is still string;

2. JSON-specific formatting rules can be summed up as 4 words

3. JSON only accepts UTF-8 encoded characters, so the Json_encode () parameter must be UTF-8 encoded , otherwise the null character or null will be obtained.

At first, the JSON document was read by these rules, [],{} was chaotic, but saw the following passage. Source (Nanyi: Data type and JSON format)

It says that, structurally, all data can eventually be decomposed into three types :

The first type is scalar (scalar), which is a single string (string) or number (numbers), such as "Beijing", a separate word.

The second type is the sequence (sequence), which is a number of related data that are tied together in a certain order, also called an array or list, such as "Beijing, Shanghai."

The third type is mapping (mapping), a name/value pair (Name/value), which has a name and a value corresponding to it, also known as hash (hash) or dictionary (dictionary), such as "Capital: Beijing".

Now, any data type can be merged into the above three classes. An array represents a collection of ordered data, whereas an object represents a collection of unordered data. If the order of the data is important, use an array, or use the object

My [],{} Confusion is also resolved, [] corresponding to the sequence, also known as an indexed array; {} corresponds to a mapping, also known as an associative array. Source: Nanyi: Using JSON in the PHP language

The operation of Json_encode and Json_decode on the 23rd type can be understood as a conversion between a string type and a mapping or sequence, and for a scalar, it is coded escaped ( only the underlying Unicode is found, not exactly.) )

//sequence, indexed array$arr=Array(' One ', ' both ', ' three '));EchoJson_encode ($arr);//["One", "one", "three"]//map, associative array$arr=Array(' 1 ' = ' one ', ' 2 ' = '-'-', ' 3 ' = ' three '));EchoJson_encode ($arr);//{"1": "One", "2": "One", "3": "Three"}//Special description, mapped decode$json= ' {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4, ' E ': 5} ';Var_dump(Json_decode ($json));//Default Build Stdclass objectObject(StdClass)#1 (5) {["a"] = + int (1) ["B"]/= Int (2) ["C"] = Int (3) ["D"]/= Int (4) ["E"] = + int (5)}Var_dump(Json_decode ($json,true));//Plus parameter True to specify that the associative array be generatedArray(5) {["a"] = Int (1) ["B"]/= Int (2) ["C"] = Int (3) ["D"]/= Int (4) ["E"] = + int (5)}

Next two: serialization

When does serialization need to be serialized?

Complex data structures are stored in memory in the PHP script execution process, but are not available for direct transfer/storage of warehousing etc.

What is the essence of serialization?

The data structure storage will have the corresponding structures, and the serialization can be understood as the process of dimensionality reduction.

The difference between json_encode/serialize?

Is the process of serializing a string, using different rules. Self-understanding, serialize is starting with PHP 3.05 support, generating strings more compact , Json_encode is supported after PHP 5.2, readability is better.

Update differences:

JSON vs. serialized Array in database [closed]

Preferred method to store PHP arrays (Json_encode vs serialize)

The basic evaluation is that JSON is easier to read, faster, and has less storage space after serialization.

JSON is not selected in the following cases only:

1. Using PHP version is too low, not supported;

2. There are too many complex structure elements to store, more than 127 elements, and JSON will return an error;

3. Need to retain information such as class name

Thinking of json_encode/serialize caused by the storage array of a field in a database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.