Asking for a PHP two-dimensional array the most efficient way to turn one-dimensional arrays

Source: Internet
Author: User
Two-dimensional arrays:

Array(    [0] => Array        (            [cnname] => 巴宝莉        )    [1] => Array        (            [cnname] => 巴宝        ))

The conversion result is

Array('巴宝莉','巴宝');

Try not to use foreach as much as possible with PHP built-in functions

Reply content:

Two-dimensional arrays:

Array(    [0] => Array        (            [cnname] => 巴宝莉        )    [1] => Array        (            [cnname] => 巴宝        ))

The conversion result is

Array('巴宝莉','巴宝');

Try not to use foreach as much as possible with PHP built-in functions

$old = array(array("cnname"=>"巴宝莉"),array("cnname"=>"巴宝"));var_dump(array_column($old,'cnname'));

json_decode(str_replace(array('"cnname":',"{","}"),array('','',''),json_encode($arr)));效率不敢保证。


  
    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(array("cnname"=>"巴宝莉"),array("cnname"=>"巴宝"));$new = array();for($i = 0; $i < count($old); $i++){    $new[] = $old[$i]["cnname"];}var_dump($new);

Array_column ($array, ' key ') returns the specified column in the array, which can be used as a one-dimensional array to extract a column of two-dimensional array (5.5 or more to use)
Who used to know, 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.