[英]How to create an array from values of another array
This is probably a question with a very simple answer but I am unable to figure it out.这可能是一个答案非常简单的问题,但我无法弄清楚。 How could I write a foreach loop to add elements from an array to another array?
我怎么能写一个 foreach 循环来将元素从一个数组添加到另一个数组? Below I have array $A and I want to be able to write code to come up with something like $B from $A.
下面我有数组 $A,我希望能够编写代码来从 $A 中得出类似 $B 的东西。
$A = array('0'=>array('name'=>'Oscar'),'1'=>array('name'=>'Jake'));
$B = array('0'=>'Oscar','1'=>'Jake');
Here is what I came up with, but it's not working.这是我想出的,但它不起作用。
$B = array();
foreach ($A as $element=>$data) {
$B[] = $element['name'];
}
This should work:这应该有效:
$b = array_map(function($content) {
return $content['name'];
}, $a);
array_map
is a method with a callback that loops over an array and creates a new loop, depending on the return value in the function
. array_map
是一个带有回调的方法,它循环遍历一个数组并根据function
的返回值创建一个新循环。
I use array_map
instead of a foreach
loop, because array methods of PHP are optimized and improve performance when used right.我使用
array_map
而不是foreach
循环,因为 PHP 的数组方法经过优化并在正确使用时提高性能。
Docs about array_map
can be found here .可以在此处找到有关
array_map
文档。
What I always like to do, is visualize it for myself.我一直喜欢做的,就是为自己想象它。
You can use multiple ways to visualize how the variable looks like and go from there.您可以使用多种方法来可视化变量的外观并从那里开始。 My personal favorites:
我个人的最爱:
debugging
using Xdebug
Xdebug
debugging
print_r()
var_dump()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.