Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

php - getting array values without foreach loop

Is there any way to get all values in one array without using foreach loops, in this example?

<?php 
$foo = array(["type"=>"a"], ["type"=>"b"], ["type"=>"c"]);

The output I need is array("a", "b", "c")

I could accomplish it using something like this

$stack = [];

foreach($foo as $value){
  $stack[] = $value["type"];
}

var_dump($stack); 

But, I am looking for options that does not involve using foreach loops.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're using PHP 5.5+, you can use array_column(), like so:

$result = array_column($foo, 'type');

If you want an array with numeric indices, use:

$result = array_values(array_column($foo, 'type'));

If you're using a previous PHP version and can't upgrade at the moment, you can use the Userland implementation of array_column() function written by the same author.

Alternatively, you could also use array_map(). This is basically the same as a loop except that the looping is not explicitly shown.

$result = array_map(function($arr) {
   return $arr['type'];
}, $foo);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...