[ACCEPTED]-How to extract particular fields from an array-foreach

Accepted answer
Score: 11

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

edit:

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

Update:

With CakePHP 1 2.x Hash has replaced Set.

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

Score: 8

You can use for example array_map, but why do you 3 not want to use Loops? In fact every method, that 2 is able to modify the array in the way you 1 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);
Score: 5

you can use this

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

EDIT :

Assumption : if 1 title is the first element of array.

Score: 1

since 5.5, array_column does exactly what 1 you explained.

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

For more examples check the PHP manual

Score: 0

What about while loops?

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

0

Score: 0

an improved version of KingCrunch's answer:

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

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

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

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

Score: 0

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

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

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

More Related questions