PHP Array_chunk () function

Source: Internet
Author: User

Today, on the CSDN, I saw a problem.

One-dimensional arrays

PHP Code
Array (' 0 ' = ' a ',1=> ' B ',2=> ' C ',3=> ' d ',4=> ' e ',5=> ' f ');

May be very long, turn into

Array (' a ' = ' = ' B ', ' c ' = = ' d ', ' e ' = ' f ');

This is the first value as a key, the second value as value, and so on, the less than an even number, and the last null

A good solution:

$a = Array (' 0 ' = ' a ', 1 = ' B ', 2 = ' C ', 3 = ' d ', 4 = ' E ', 5 = ' f ', ' G '); foreach (Array_chunk ($a, 2 As $t) {$b [$t [0]] =! Empty ($t [1])? $t [1]: null;} Var_dump ($b);

Focus on the Array_chunk () function, the Array_chunk () function splits an array into a new array block.

Example 1
<?php$a=array ("A" = "Cat", "b" = "Dog", "c" = "Horse", "D" and "Cow");p Rint_r (Array_chunk ($a, 2));? >

Output:

Array ([0] = = Array ([0] = Cat [1] = Dog) [1] = = Array ([0] = = Horse [1] = Cow))


Example 2
<?php$a=array ("A" = "Cat", "b" = "Dog", "c" = "Horse", "D" and "Cow");p Rint_r (Array_chunk ($a, 2,true));? >

Output:

Array ([0] = = Array ([a] = Cat [b] = Dog) [1] = = Array ([c] = = Horse [d] = = Cow))

It is easy to see that the third parameter, if you do some projects, you need to return key to 0, you can quickly form

PHP Array_chunk () function

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.