php 如何将特定的数组键和值提取到另一个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10328780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract specific array keys and values to another array?
提问by Pierre
I have an array of arrays like so:
我有一个像这样的数组数组:
array( array(), array(), array(), array() );
the arrays inside the main array contain 4 keys and their values. The keys are the same among all arrays like this:
主数组内的数组包含 4 个键及其值。所有数组中的键都相同,如下所示:
array( 'id' => 'post_1',
'desc' => 'Description 1',
'type' => 'type1',
'title' => 'Title'
);
array( 'id' => 'post_2',
'desc' => 'Description 2',
'type' => 'type2',
'title' => 'Title'
);
So I want to create another array and extract the idand typevalues and put them in a new array like this:
所以我想创建另一个数组并提取id和type值并将它们放入一个新数组中,如下所示:
array( 'post_1' => 'type1', 'post_2' => 'type2'); // and so on
The keys in this array will be the value of idkey old arrays and their value will be the value of the typekey.
此数组中的键将是id键旧数组的值,它们的值将是type键的值。
So is it possible to achieve this? I tried searching php.net Array Functionsbut I don't know which function to use?
那么有可能实现这一目标吗?我尝试搜索php.net 数组函数,但我不知道要使用哪个函数?
采纳答案by deceze
Just use a good ol' loop:
只需使用一个好的 ol' 循环:
$newArray = array();
foreach ($oldArray as $entry) {
$newArray[$entry['id']] = $entry['type'];
}
回答by enoyhs
PHP 5.5 introduced an array function that does exactly what you want. I'm answering this in hopes that it may help someone in future with this question.
PHP 5.5 引入了一个数组函数,它完全符合您的要求。我正在回答这个问题,希望它可以帮助将来解决这个问题的人。
The function that does this is array_column.
To get what you wanted you would write:
执行此操作的函数是array_column. 为了得到你想要的东西,你会写:
array_column($oldArray, 'type', 'id');
To use it on lower versions of PHP either use the accepted answer or take a look at how this function was implemented in PHP and use this library: https://github.com/ramsey/array_column
要在较低版本的 PHP 上使用它,请使用已接受的答案或查看此函数在 PHP 中的实现方式并使用此库:https: //github.com/ramsey/array_column

