Home > Backend Development > PHP Tutorial > 求教一个PHP二维数组转一维数组最有效率的方法

求教一个PHP二维数组转一维数组最有效率的方法

WBOY
Release: 2016-06-06 20:23:22
Original
1439 people have browsed it

二维数组:

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

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

)</code>
Copy after login
Copy after login

转换结果为

<code>Array('巴宝莉','巴宝');</code>
Copy after login
Copy after login

请尽量不要使用foreach,尽量使用php内置函数

回复内容:

二维数组:

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

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

)</code>
Copy after login
Copy after login

转换结果为

<code>Array('巴宝莉','巴宝');</code>
Copy after login
Copy after login

请尽量不要使用foreach,尽量使用php内置函数

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

<code>json_decode(str_replace(array('"cnname":',"{","}"),array('','',''),json_encode($arr)));
效率不敢保证。</code>
Copy after login

<code class="php"><?php $records = array(
    array(
        'id' => 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);
?></code>
Copy after login

Result

<code class="php">Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)</code>
Copy after login

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

<code>$old = array(array("cnname"=>"巴宝莉"),array("cnname"=>"巴宝"));

$new = array();
for($i = 0; $i </code>
Copy after login

array_column($array,'key') 返回数组中指定的一列,可以用作提取二维数组某一列做一维数组(5.5以上才能使用)
谁用谁知道,我自己的笔记~项目中碰到过的。。

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template