开发者

How to extract particular fields from an array [duplicate]

This question already has answers here: Is there a function to extract a 'column' from an array in PHP? 开发者_StackOverflow社区 (15 answers) Closed 9 months ago.

I have an array that looks

$articles = array([0] => array('title' => 'When ....',
                               'description' => '....', 
                               'created' => '2011-02-21'
                              ), 
                  [1] => array('title' => 'Something ....',
                               'description' => 'When ....', 
                               'created' => '2011-02-21'
                              ),
            );

I want to extract only the titles. Is there anyway to retrieve the titles without using for and foreach loops. I dont mind the title becomes a single string. I was thinking implode the array but that adds description and created.


considering its CakePHP, $titles = Set::extract('/title', $articles);

edit:

http://book.cakephp.org/view/1487/Set

Update:

With CakePHP 2.x Hash has replaced Set.

$titles = Hash::extract($articles, '{n}.title');


You can use for example array_map, but why do you not want to use Loops? In fact every method, that is able to modify the array in the way you want it, will iterate over it.

function reduce_to_title ($item) {
  return $item['title'];
};
$titles = array_map('reduce_to_title', $articles);

Or since PHP>=5.3

$titles = array_map(function ($item) {
  return $item['title'];
}, $articles);


you can use this

print_r(array_map('array_shift', $articles));

EDIT :

Assumption : if title is the first element of array.


since 5.5, array_column does exactly what you explained.

$titles = array_column($articles, "title"); // [0=>"When",1=>"Something"]

For more examples check the PHP manual


What about while loops?

reset($articles); while($a = each($articles)){echo $a['value']['title'];}


an improved version of KingCrunch's answer:

function get_column(&$array,$column) {
  foreach ($array as $value) {
    $ret[]=$value[$column];
  }
  return $ret;
}

this is pretty universal function and can be put into some library, and then called with just single line, which is shorter than in every other answer:

$titles = get_column($articles, 'title');

Update
However, it seems that cake already have such a function, so, the only proper answer is How to extract particular fields from an array


Hey, since you're using CakePHP, why don't you just add title to the fields array in your find()? For example, the following,

$this->Article-find('all', array('fields'=>'Article.title'));

will pull only the titles of all matching Articles in the database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜