Home >Backend Development >PHP Tutorial >重组数组 - php 将任意二维数组转换一维数组(键值对) 想问下有没有更好的办法。

重组数组 - php 将任意二维数组转换一维数组(键值对) 想问下有没有更好的办法。

WBOY
WBOYOriginal
2016-06-06 20:36:561275browse

我的方法是这样的:

<code><?php $a = [
    [
        'id' => 33, // 这里的键名不固定
        'name' => 'aaa',
    ],
    [
        'id' => 22,
        'name' => 'bbb'
    ]
];

$dat = [];
foreach ($a as $b) {
    list($k, $v) = array_values($b);
    $dat[$k] = $v;
}

var_export($dat); // 输出:array ( 33 => 'aaa', 22 => 'bbb', )
</code>

回复内容:

我的方法是这样的:

<code><?php $a = [
    [
        'id' => 33, // 这里的键名不固定
        'name' => 'aaa',
    ],
    [
        'id' => 22,
        'name' => 'bbb'
    ]
];

$dat = [];
foreach ($a as $b) {
    list($k, $v) = array_values($b);
    $dat[$k] = $v;
}

var_export($dat); // 输出:array ( 33 => 'aaa', 22 => 'bbb', )
</code>

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

Statement:
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