How to convert a PHP two-dimensional array to one-dimensional array

Source: Internet
Author: User
Two-dimensional array: {code...} is converted to {code...}. Please try not to use foreach. Try to use a two-dimensional array of php built-in functions:

Array ([0] => Array ([cnname] => Burberry) [1] => Array ([cnname] => Baobao ))

The conversion result is

Array ('burberry ', 'baobao ');

Please try not to use foreach, and try to use php built-in functions

Reply content:

Two-dimensional array:

Array ([0] => Array ([cnname] => Burberry) [1] => Array ([cnname] => Baobao ))

The conversion result is

Array ('burberry ', 'baobao ');

Please try not to use foreach, and try to use php built-in functions

$ Old = array ("cnname" => "Burberry"), array ("cnname" => "Baobao"); var_dump (array_column ($ old, 'cnname '));

Json_decode (str_replace (array ('"cnname":', "{", "}"), array ('','',''), json_encode ($ arr); efficiency cannot be guaranteed.


   2135,        'first_name' => 'John',        'last_name' => 'Doe',    ),    array(        'id' => 3245,        'first_name' => 'Sally',        'last_name' => 'Smith',    ),    array(        'id' => 5342,        'first_name' => 'Jane',        'last_name' => 'Jones',    ),    array(        'id' => 5623,        'first_name' => 'Peter',        'last_name' => 'Doe',    )); $first_names = array_column($records, 'first_name');print_r($first_names);?>

Result

Array(    [0] => John    [1] => Sally    [2] => Jane    [3] => Peter)

Http://php.net/manual/ja/function.array-column.php

$ Old = array ("cnname" => "Burberry"), array ("cnname" => "Baobao"); $ new = array (); for ($ I = 0; $ I <count ($ old); $ I ++) {$ new [] = $ old [$ I] ["cnname"];} var_dump ($ new );

Array_column ($ array, 'key') returns a specified column in the array, which can be used to extract a column of a two-dimensional array and make a one-dimensional array (more than 5.5 can be used)
Who knows, my own notes ~ Encountered in the project ..

array_map(function($a){return $a['cnname']},$arr)

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.